A Play Framework login/authentication example project

Without an example it can be hard to understand how user authentication works in a Play Framework application, so I just created a project on Github named PlayFrameworkLoginAuthenticationExample that demonstrates one way to implement login authentication in a Play Framework 2.6 application.

I can write more about it if people are interested, but the highlights go like this:

  • If you have a current version of SBT installed, you can download the project and immediately run it with the sbt run command
  • I removed all the database-access code from the project, so you can immediately access the http://localhost:9000/users/login URL
  • When you access that URL the routes file sends control to the showLoginForm method in the UserController class; it displays the userLogin.scala.html template
  • You can see in the UserDao that the username and password are both foo
  • When you attempt to login, the routes file sends the user form data to the processLoginAttempt in the UserController class
  • If the login attempt succeeds, control is sent to the showLandingPage action in the LandingPageController class; it shows the loginLandingPage.scala.html template, which includes a “logout” link; it also shows a Flash message that the login succeeded
  • User authentication is implemented in the AuthenticatedUserAction class
  • To make sure that an action can only be accessed by an authenticated user, the method should use an instance of AuthenticatedUserAction, as shown by the showLandingPage method in the LandingPageController controller:
def showLandingPage() = authenticatedUserAction { implicit request: Request[AnyContent] =>
    Ok(views.html.loginLandingPage(logoutUrl))
}

What it looks like

Here’s what this little starter application looks like. First, the login page:

Play Framework authentication: Login page

Next, the simple landing page with the Flash message:

Play Framework authentication: Landing page with Flash message

Next, what you see when you log out:

Play Framework authentication: Logout page

And finally, what you see if you attempt to access the landing page when you’re not logged in:

Play Framework authentication: Landing page when you're not logged in

Admittedly not too exciting, but it shows the authentication basics.

Summary

If you wanted to see an example of a Play Framework 2.6 login/authentication application, I hope this project is helpful. I think it follows the Play Action Composition docs pretty faithfully. If people have questions about the project I’ll be glad to write more here, but I hope this is helpful as is.

P.S. — If you’re writing a Play Framework server application with a JavaScript client front-end you’ll have to do things a little differently, but hopefully this example can help a little bit in that use case as well.