Friday, July 8, 2011

SPRING SECURITY - Step By Step

This tutorial assumes that you have setup a web project with the Spring Security Dependencies added to your build path. Those of you who don't have the dependencies, Use Maven dependencies for Spring Security to configure the Spring Security dependencies in your project.

1. To get started with the spring security, we need to include the Security namespace to the spring configurations. The Security namespace is available in the Spring-config jar file.


<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
                        
</beans:beans>

2. We need to add the following filter declaration to our web.xml. This filter provides a hook to the Spring Security Framework.

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/conf/ApplicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

3. Enable the web security using the <http> element in your SpringSecurity.xml

<http auto-config="true">
<!--  Any user can access the login page -->
<intercept-url pattern="/login.do" filters="none" />


<!-- Only users with Role: ROLE_USER would be able to access other URLs -->
<intercept-url pattern="/**" access="ROLE_USER" />
</http>

The above configuration indicates that we want all the URLs in our application to be secured and should have the role ROLE_USER to access the application.

4. For testing the spring security, we need to create some sample user ids in the Spring configuration file. In general, these security validations are done using the users in database or LDAP.

<authentication-provider>
<user-service>
<user name="vijay" password="vijay" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="sam" password="sam" authorities="ROLE_GUEST" />
</user-service>
</authentication-provider>

Once the above configurations are done and the view pages and controllers are created, launch the application and the unauthenticated users accessing any URL other than login.do would get redirected to login page.

Login Screen

This is the page automatically generated by the Spring Security and displayed to the user.

No comments:

Post a Comment