This is a Play application illustrating a simple approach to authentication and authorization.
Authentication is done in the following way:
-
The models package implements the UserInfo and UserInfoDB classes to hold credential information. Credentials are initialized in the Global class.
-
The Login view provides a simple login form. The LoginFormData.validate() method determines if the login succeeds and raises ValidationErrors if invalid credentials are entered.
-
The Login controller method adds the authenticated user's email to the session object, or else returns the Login view with errors.
Authorization is done in the following way:
-
The Secured class supports authorization by extending the Security.Authenticator class and overriding the getUsername() and onUnauthorized() methods. These methods are used to restrict access to the profile page. This class also implements helper methods (getUser(), isLoggedIn(), and getUserInfo()) that enable controllers to adjust the view depending upon whether the user is logged in or not.
-
The Application controller class annotates the controller methods that requires authenticated users (logout() and profile()) with @Security.Authenticated(Secured.java).
-
The Main.scala.html template implements a context sensitive navbar that displays different links depending upon whether the user is authenticated or unauthenticated.
Obvious shortcomings of this approach:
- Credentials sent "in the clear" (i.e. via http, not https).
- Credentials stored "in the clear".
- No registration workflow (i.e. email confirmation.)
- No support for third-party authentication (google, facebook, etc.)
If you require "production quality" authentication and authorization, you should consider a Play plugin such as play-authenticate, SecureSocial, and/or Deadbolt 2. They are slightly more complicated to use but provide mechanisms to address these issues.
Click the image below to watch a 15 minute walkthrough of this system.