Friday, January 18, 2013

Spring Security - First Steps

Here are my notes on getting started with using Spring Security with web applications.This  post focuses on authentication and securing web requests.

The first thing to do when using Spring with web applications is bootstrapping the application context. To do that add a context listener to the web.xml file.
Notice that there are 2 spring configuration files. The idea here is to keep the security related configuration in a separate xml configuration file of its own.
The next thing to do is to add a filter which will intercept the requests and delegate to a 'spring-context-aware' class which will add the actual security related functionality.
Now to configure the actual authentication and role based url access , add the following snippet to the applicationContext-security.xml
<http auto-config="true">
 <intercept-url  pattern="/test/**" access="ROLE_USER" />
 <intercept-url  pattern="*/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
What we have done above is to configure spring so that whenever there is a request for any url under the test folder under the context root, spring checks whether the user is logged in and has the authority 'ROLE_USER'. If the user is not logged in, she is taken to the login page.

But where does the actual authentication happen? Spring provides a host of production ready authentication providers to do the actual authentication against a datasource or ldap or through other means. For this post , we'll look at the simplest case where the usernames and password are read from the spring application context file.
        <user name="nandini" password="nnnnppp" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="sanjucta" password="sssppp" authorities="ROLE_USER" />
So there we have it, we have configured spring security to be able to intercept web requests and force the user to login if he wants access to access 'restricted' urls.The username / password combination that the user enters is checked against the user names and passwords configured in security configuration file .

No comments: