Formerly called ACEGI Security for Spring, the re-branded Spring Security 2.0 has delivered on its promises of making it simpler to use and improving developer productivity. Already considered as the Java platform's most widely used enterprise security framework with over 250,000 downloads from SourceForge, Spring Security 2.0 provides a host of new features.
This article outlines how to convert your existing ACEGI based Spring application to use Spring Security 2.0.
Spring Security 2.0 has recently been released as a replacement to ACEGI and it provides a host of new security features:
Currently I work on a Spring web application that uses ACEGI to control access to the secure resources. Users are stored in a database and as such we have configured ACEGI to use a JDBC based UserDetails Service. Likewise, all of our web resources are stored in the database and ACEGI is configure to use a custom AbstractFilterInvocationDefinitionSource to check authorization details for each request.
With the release of Spring Security 2.0 I would like to see if I can replace ACEGI and keep the current ability to use the database as our source of authentication and authorization instead of the XML configuration files (as most examples demonstrate).
Here are the steps that I took...
<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>
<http auto-config="true" access-denied-page="/403.jsp"> <intercept-url pattern="/index.jsp" access="ROLE_ADMINISTRATOR,ROLE_USER"/> <intercept-url pattern="/securePage.jsp" access="ROLE_ADMINISTRATOR"/> <intercept-url pattern="/**" access="ROLE_ANONYMOUS" /> </http>Replace this with:
<authentication-manager alias="authenticationManager"/> <beans:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased"> <beans:property name="allowIfAllAbstainDecisions" value="false"/> <beans:property name="decisionVoters"> <beans:list> <beans:bean class="org.springframework.security.vote.RoleVoter"/> <beans:bean class="org.springframework.security.vote.AuthenticatedVoter"/> </beans:list> </beans:property> </beans:bean> <beans:bean id="filterInvocationInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor"> <beans:property name="authenticationManager" ref="authenticationManager"/> <beans:property name="accessDecisionManager" ref="accessDecisionManager"/> <beans:property name="objectDefinitionSource" ref="secureResourceFilter" /> </beans:bean> <beans:bean id="secureResourceFilter" class="org.security.SecureFilter.MySecureResourceFilter" /> <http auto-config="true" access-denied-page="/403.jsp"> <concurrent-session-control max-sessions="1" exception-if-maximum-exceeded="true" /> <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp" default-target-url="/index.jsp" /> <logout logout-success-url="/login.jsp"/> </http>
package org.security.SecureFilter; import java.util.Collection; import java.util.List; import org.springframework.security.ConfigAttributeDefinition; import org.springframework.security.ConfigAttributeEditor; import org.springframework.security.intercept.web.FilterInvocation; import org.springframework.security.intercept.web.FilterInvocationDefinitionSource; public class MySecureResourceFilter implements FilterInvocationDefinitionSource { public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException { FilterInvocation filterInvocation = (FilterInvocation) filter; String url = filterInvocation.getRequestUrl(); // create a resource object that represents this Url object Resource resource = new Resource(url); if (resource == null) return null; else{ ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor(); // get the Roles that can access this Url List<Role> roles = resource.getRoles(); StringBuffer rolesList = new StringBuffer(); for (Role role : roles){ rolesList.append(role.getName()); rolesList.append(","); } // don't want to end with a "," so remove the last "," if (rolesList.length() > 0) rolesList.replace(rolesList.length()-1, rolesList.length()+1, ""); configAttrEditor.setAsText(rolesList.toString()); return (ConfigAttributeDefinition) configAttrEditor.getValue(); } } public Collection getConfigAttributeDefinitions() { return null; } public boolean supports(Class arg0) { return true; } }This getAttributes() method above essentially returns the name of Authorities (which I call Roles) that are allowed access to the current Url.
<authentication-provider> <user-service> <user name="rod" password="password" authorities="ROLE_SUPERVISOR, ROLE_USER" /> <user name="dianne" password="password" authorities="ROLE_USER,ROLE_TELLER" /> <user name="scott" password="password" authorities="ROLE_USER" /> <user name="peter" password="password" authorities="ROLE_USER" /> </user-service> </authentication-provider>You could replace these examples with this configuration so that you can read the user details straight from the database like this:
<authentication-provider> <jdbc-user-service data-source-ref="dataSource" /> </authentication-provider>While this is a very fast and easy way to configure database based security it does mean that you have to conform to a default databases schema. By default, the <jdbc-user-service> requires the following tables: user, authorities, groups, group_members and group_authorities.
<authentication-provider> <jdbc-user-service data-source-ref="dataSource" users-by-username-query="SELECT U.username, U.password, U.accountEnabled AS 'enabled' FROM User U where U.username=?" authorities-by-username-query="SELECT U.username, R.name as 'authority' FROM User U JOIN Authority A ON u.id = A.userId JOIN Role R ON R.id = A.roleId WHERE U.username=?"/> </authentication-provider>By adding the users-by-username-query and authorities-by-username-query properties you are able to override the default SQL statements with your own. As in ACEGI security you must make sure that the columns that your SQL statement returns is the same as what Spring Security expects. There is a another property group-authorities-by-username-query which I am not using and have therefore left it out of this example, but it works in exactly the same manner as the other two SQL statements.
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost/db_name?useUnicode=true&characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="pwd"/> </bean>
<input type="text" name="j_username" id="j_username"/> <input type="password" name="j_password" id="j_password"/>However you must set the action property of your <form> to point to j_spring_security_check and not j_acegi_security_check .
<form method="post" id="loginForm" action="<c:url value='j_spring_security_check'/>"There are a few places in our application where the user can logout, this is a link that redirects the logout request to the security framework so that it can be handled accordingly. This needs to be changed from j_acegi_logout to j_spring_security_logout .
<a href='<c:url value="j_spring_security_logout"/>'>Logout</a>
This short guide on how to configure Spring Security 2.0 with access to resources stored in a database does not come close to illustrating the host of new features that are available in Spring Security 2.0, however I think that it does show some of the most commonly used abilities of the framework and I hope that you will find it useful.
One of the benefits of Spring Security 2.0 over ACEGI is the ability to write more consice configuration files, this is clearly shown when I compare my old ACEGI configration (172 lines) file to my new one (42 lines).
Here is my complete securityContext.xml file:
<?xml version="1.0" encoding="UTF-8"?> <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-2.0.xsd,http://www.springframework.org/schema/security,http://www.springframework.org/schema/security/spring-security-2.0.xsd"> <authentication-manager alias="authenticationManager"/> <beans:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased"> <beans:property name="allowIfAllAbstainDecisions" value="false"/> <beans:property name="decisionVoters"> <beans:list> <beans:bean class="org.springframework.security.vote.RoleVoter"/> <beans:bean class="org.springframework.security.vote.AuthenticatedVoter"/> </beans:list> </beans:property> </beans:bean> <beans:bean id="filterInvocationInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor"> <beans:property name="authenticationManager" ref="authenticationManager"/> <beans:property name="accessDecisionManager" ref="accessDecisionManager"/> <beans:property name="objectDefinitionSource" ref="secureResourceFilter" /> </beans:bean> <beans:bean id="secureResourceFilter" class="org.security.SecureFilter.MySecureResourceFilter" /> <http auto-config="true" access-denied-page="/403.jsp"> <concurrent-session-control max-sessions="1" exception-if-maximum-exceeded="true" /> <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp" default-target-url="/index.jsp" /> <logout logout-success-url="/login.jsp"/> </http> <beans:bean id="loggerListener" class="org.springframework.security.event.authentication.LoggerListener"/> <authentication-provider> <jdbc-user-service data-source-ref="dataSource" users-by-username-query="SELECT U.username, U.password, U.accountEnabled AS 'enabled' FROM User U where U.username=?" authorities-by-username-query="SELECT U.username, R.name as 'authority' FROM User U JOIN Authority A ON u.id = A.userId JOIN Role R ON R.id = A.roleId WHERE U.username=?" /> </authentication-provider> </beans:beans>
As I said in step 1, downloading Spring Security was the trickiest step of all. From there on it was plain sailing...