Tuesday, December 1, 2009

Simple Authentication and Authorization with EasyWeb4J

This post demonstrates the implementation of a simple password based Authentication and Authorization system built with EasyWeb4J. This post will demonstrate the hashing API of EasyWeb4J (including salt generation) and put to use EasyWeb4J's simplified request filtering for authorization.

When a user signs up his password is combined with a random salt of 10 bytes. This is then hashed using MD5 algorithm. The salt and the password hash are stored. During login the user is retrieved by his username and the entered password is hashed and compared against the original hash.

Download the complete source code for this application.

Create a new EasyWeb4J Hibernate Project as described in the tutorial. Configure hibernate as shown below.

src/main/resources/hibernate.xml

The Model

src/main/java/net/auth/models/User.java

The encryptPassword method generates a random salt and encrypts the clear text password using MD5 algorithm and the salt, using EasyWeb4J's hashing API. The matchesPassword method takes a clear text password input by the user, hashes it using the previously generated salt and compares it with the original hashed password.

The Controllers

This sample application has three controllers.
  1. UsersController - Handles user signup.
  2. SessionsController - Handles login and logout.
  3. HomeController - The actual application which needs to be secured by requiring login.
src/main/java/net/auth/controllers/UsersController.java

Not much magic there. Just a standard controller to create a user after encrypting the entered password.

Authentication

src/main/java/net/auth/controllers/SessionsController.java

This controller authenticates a user from login screen and redirects them to the secure home page after storing the user ID in session. If login fails, it redirects to the login page back after setting a message in flash. Also, while displaying the login page it checks whether the user has already logged in and if so directly redirects them to home page without requesting credentials.

Authorization

While there is only one controller in this example whose requests need to be secured, in real applications there would be several. Hence we create an abstract controller which will override the filterRequest() method to perform authorization during each request.

src/main/java/net/auth/controllers/SecureController.java

It verifies whether a user is currently logged in and if so, sets the real user as a request attribute. This would be used to greet the user by his full name.

Finally we have the home controller which in this sample does nothing other than rendering the index view.

src/main/java/net/auth/controllers/HomeController.java

There we have a complete DB based login system. :)

0 comments:

Post a Comment