Monday, 13 August 2012

Spring Security : Documenting Essentials

I was looking at Spring Security recently and thought I’d quickly put it in a sample project. I poked around on the web and got quite a few examples.

However, though they were good, I could not use them as is. The examples don’t use the latest version, Spring 3. The data persistence is not covered adequately, and many a time do not use Hibernate. They put emphasis on details, but do not summarize the important steps.

I will give the bare bone essentials of implementing Spring Security. One thing to note is that, to use spring security, you need to use Spring MVC. You can’t plug in spring security on its own without Spring MVC.

The spring context xml that you will require is:
You can put your username, password, enabled columns in table of any name (table1 or tumbuktu) and role & role names in table of any name (table2 or jambapamba). Of course, I used USERS table (User entity) with USERNAME, PASSWORD, ENABLED as the columns (properties). I used ROLES table (Role entity) with ROLE as the column (property).

The two key things on the security side are:
First, User should implement the interface UserDetails. It should have a property called Authorities of type Collection. You need a setter for Authorities that takes roles as the data input.

Second, you need to implement the UserServiceImpl (name can be anything that is configured as the authentication-manager in the xml) that implements UserDetailsService interface with the method loadUserByUsername. Given a string, the method has to retrieve the user with that username from the database. It also has to retrieve the roles for that user and pass that roles to the setter for Authorities. The method should return the user.

Given below is the java code -

On the MVC part, you will need a login.jsp that has a form whose action is j_spring_security_check. One controller (any file with @Controller annotation) with a method called login and RequestMapped to "/login" is the final piece. And that's it. Given below are the extracts.

Technical documentation and tutorials have to be improved. Programmers, and indeed any user, need documentation with actionable essentials and quick how-to’s. Instead, a lot of available material is not 100% useful and people have to spend time filling in the gaps.

No comments:

Post a Comment