Home > tech > Using Spring Security to Secure an Existing Web Application

Using Spring Security to Secure an Existing Web Application

September 15th, 2010 Leave a comment Go to comments

Recently I was involved in securing a web application using Spring Security. The web application already had a “home-grown” security module in place. Therefore, adding Spring Security to the existing application, required going beyond the “intelligent defaults” and peeling the layers to understand the touch points between Spring Security and the web application.

Although Spring Security is highly configurable and extend-able, and follows the coding to interfaces paradigm to the T, it is still geared towards modern applications, aka web applications. To really get a handle on what’s going on under the covers, we’ll also look at securing a Java Application, with no servlet container to run in.

Those who are new to Spring Security, or those who have only seen it in it’s Acegi days, will notice a difference in the way Spring Security is configured. Instead of specifying all the relevant beans in the Spring context, Spring Security makes use of Spring Namespaces.

Spring namespaces allow the user to specify some elements in a Spring application context and by merely including or excluding some elements, the Spring core classes will register the appropriate classes as Spring managed beans. (The only way to see what namespace elements and attributes are available would be to look at the security namespace schema. Although the documentation has talked about the namespace it is not comprehensive; what I found a more practical was to get the Spring plugin for Eclipse and allow code-completion to tell you what’s available).

Since web applications is where Spring Security provides the most out-of-the-box features, let’s start with the web.xml. The following lines tell the servlet container to add a Virtual Filter Chain to all URLs ensuring that the class DelegatingFilterProxy is called before passing on the HttpRequest to any servlet that may be configured additionally.



springSecurityFilterChain is a Spring managed bean that is configured by the Spring namespace when the container starts up. The DelegatingFilterProxy is where all the other approximately dozen filters are configured.
With that background let’s start by looking at Authentication.


The purpose of authentication is two fold: Check the users credentials and if successful  then place an Authentication object in a ThreadLocal<SecurityContext> variable.

Lets look at a web application scenario. Like stated earlier, the URL is passed through a series of filters. Here is the chronology of events:

1. One of the filters called the UsernamePasswordAuthenticationFilter creates a UsernamePasswordAuthenticationToken (which is a subclass of Authentication)  and provides it to the ProviderManager. At this point the UsenamePasswordAuthenticationToken contains just the entered username and password.

2. The ProviderManager (which is an instance of AuthenticationManager) loops through all the AuthenticationProviders that are registered with it and attempts to pass the token to any provider that accepts it

3. Each provider calls it’s authenticate(…) method. One such provider is the DaoAuthenticationProvider that has been configured with a UserDetailService. The UserDetailService is where SQL can be specified to access your custom schema and return a UserDetails object. This UserDetails object  is used to fill out the missing password and authorities in the UsernamePasswordAuthenticationToken. An example of a customized UserDetailService is here.

4. The ProviderManager, if configured with a PasswordEncoder, compares the password entered to the (possibly decrypted) password from the UserDetails object and if it matches, then it passes on the Authentication object (UsernamePasswordAuthenticationToken) to the next filter

5. The SecurityContextpersistenceFilter persists the Authentication object in a SecurityContextHolder that is bound to a ThreadLocal<SecurityContext> variable.

All the above happens if you configure the namespace like so:

	    <authentication-provider user-service-ref='acmeUserDetailsService' >
	      <password-encoder ref="passwordEncoder" />

	  <beans:bean id="acmeUserDetailsService"
	    <beans:property name="dataSource" ref="pooledDataSource"/>

	 <beans:bean id="passwordEncoder" class="com.acme.security.AcmePasswordEncoder" />

Now let us look at how we can achieve (almost) the same effect if we were to secure a java application. There are no servlet filters to rely on so we have to resort to the APIs. Assuming you have a swing application, you will have to make the UI that accepts a username and password and then call the following code:

public boolean login(String username, String password) {

       boolean boo = false;
       UsernamePasswordAuthenticationToken token =
		new UsernamePasswordAuthenticationToken(username, password);

       JdbcDaoImpl userDetailService = new JdbcDaoImpl();
       UserDetails ud = userDetailService.loadUserByUsername(username);
       UsernamePasswordAuthenticationToken token =
		new UsernamePasswordAuthenticationToken(username, password, ud.getAuthorities());

	try {
		Authentication auth = authenticationManager.authenticate(token);
		SecurityContext securityContext = new SecurityContext ();

		//Places in ThredLocal for future retrieval
		boo =  true;

	} catch (AuthenticationException e) {
		//log it and rethrow

	return boo;

Note that the userDetailService above is the out-of-the-box JdbcDaoImpl, but it very well could be a customized UserDetailService as downloadable fron here. Also the authenticationManager is the Spring managed bean that is registered by Spring Security as shown above.

Once the Authentication object is available as a ThreadLocal variable, it can be accessed from anywhere in the application (even the Service or DAO layers) using this.


Now that we have identified who is accessing the web application via the Authentication object, let’s look at details of what is accessible.

Let’s define a few key entities are shown in the picture below.

There is some confusion on what constitutes an Authority as it is interchangeably called Role or Permission throughout the documentation, but essentially they are the same thing.
A Role/Authority/Permission is a granular definition of a business use case. For example: ACCESS_ACCOUNT, DELETE_INVOICE, TRANSFER_BALANCE etc could be all treated as business use cases.
A Group, can have multiple Authorities and typically represents what is commonly called outside the Spring Security world, a ‘role’. For example a business department or function like ACCOUNTS, SALES, ADMIN etc could be Group.
A Resource is anything that needs protected. In the context of Spring Security it could be a URL, a method on a Spring managed bean (service bean) or a domain object.

To add to the confusion, there is the concept of a RoleHierarchy that allows you to nest Authorities. That makes it tempting to use a RoleHierarchy to model aggregations of Authorities by using only nested Authorities. But that is not recommended because nesting Authority aggregations is typically an admin function. This nesting relationship of roles is typically not stored in a database (at least there is no schema that Spring supports to persist role hierarchies).

And finally, Spring Security allows you to map Users to Groups OR Users to Authorities, bypassing Groups completely! That opens a host of ways to configure authorization. I’ll leave it at this: Given that there is no out-of-the-box way to persist Role hierarchies, and given that mapping macro business functions to granular business use cases is usually done via an admin UI, it’s best to leave Role hierarchies to when it’s absolutely necessary and stick to the scenario on the picture above.

In the picture above, we see two sections: resources-authorities mapping and users-groups-authorities mapping. The first is stored in xml configuration files and the second in database tables. That is a desirable goal:

We decide what resource can be mapped to what authorities at development time and therefore we set that up in code (security-context.xml, typically). So, for instance, we can secure URLs, say that sales/*.jsp can be accessed only by those users that have the SALES_VIEW and SALES_CREATE authorities. Similarly, we can secure service methods by assigning , for instance, the DefaultServiceImpl.createNewSale() method to the SALES_CREATE authority.

On the other hand, the users-groups-authorities relationship is more fluid and can be assigned at run time, via admin screens/pages that manipulate this relationship in a database. For instance, via an admin screen we would like to assign the SALES_VIEW and SALES_CREATE authorities to the SALES group. Then, since user Bob recently moved into the Sales department, we can assign him to the Sales group (and re-assign Jill from the SALES group to the ACCOUNTS group).

In that manner Bob ends up accessing sales/*.jsp and createNewSale() service and Jill, who has been removed from the Sales group, finds she cannot.

That has hopefully helped clear some confusion about these terms. Now lets see how to use them.
Spring Security provides classes and database schemas/table definitions to manage/store the group-user relationship and the group-authority relationship.

The authority-resource relationship however can be broken up as follows:

Securing URLs: This is achieved by the http and intercept-url elements in the security namespace.
Securing service methods: This is achieved by adding the intercept-method element to the bean definition in a spring context file
Securing business domain objects: This is achieved by configuring Spring ACLs. This is a combination of Database tables and Spring configuration. There is also a good article on this topic here.

With that background let’s look at securing URLs and securing methods. We will not cover domain level security (Spring ACLs) in this post.

Securing URLs

The filter specified in the web.xml called springSecurityFilterChain automatically loads a FilterChainProxy where the rest of the filters that are needed for web application security are configured.

One of those filters is a FilterSecurityInterceptor which is responsible for authorization. Here is the chronology of what happens when a url has to be authorized:
1. The FilterSecurityInterceptor is an instance of AbstractSecurityInterceptor.
2. The AbstractSecurityInterceptor defines the workflow (described here) to to actually carry out the authorization by using an instance of the AccessDecisionManager interface called AffirmativeBased (default).
3. The AffirmativeBased AccessDecisionManager is configured by default with a series of DecisionVoters. An AffirmativeBased AccessDecisionManager means that if any one of it’s configured decisionVoters votes a ‘yes’, the rest of the voting process is aborted and the final vote is a ‘yes’.
4. One of the DecisionVoters is RoleVoter that is responsible for voting on ConfigAttributes that are the acutal GrantedAuthorities name strings. By default the GrantedAuthorities are prefixed with ‘ROLE_’.
5. Another DecisionVoter is AuthenticatedVoter that is responsible for voting on strings like: IS_AUTHENTICATED_FULLY or IS_AUTHENTICATED_REMEMBERED or IS_AUTHENTICATED_ANONYMOUSLY.
6. For expressions, new in release 3.0 is the WebExpressionVoter. This will be used if expressions are used.

To do all the above, the following needs added to the spring security context:

<http auto-config='true' use-expressions="true">
	<intercept-url pattern="/login.jsp" access="permitAll" />
	<intercept-url pattern="/secure/**" access="hasRole('ACCOUNT_DELETE')" />
	<intercept-url pattern="/**" access="isAuthenticated()" />

	<form-login login-page="/login.jsp"  authentication-failure-url="/login.jsp?login_error=1" login-processing-url="/loginURL"/>
	<logout invalidate-session="true" />

The above causes any URL to be accessed only by authenticated users. Any url that begins with ‘secure’ will need ACCOUNT_DELETE authority granted to that user. login.jsp is accessible by all. use-expressions tells the Spring security classes to register the WebExpressionVoter (instead of the RoleVoter) as a decisionVoter on the AffirmativeBased AccessDecisionManager.

Securing Service Level Methods

For those familiar with Spring’s AoP features, this functionality should come as no surprise. There are three ways you can secure methods: Use annotations as described here . Use point cuts on certain methods on Spring managed beans, much like transaction semantics.Lastly we can configure method-level protection by using  intercept-method in the bean definition itself. Here is an example of that:

<beans:bean id="acmeService" class="com.acme.service.AcmeService">
<intercept-methods access-decision-manager-ref="customAccessDecisionManager">
  <protect access="SALES_CREATE" method="businessMethodToCreateASale"/>
<beans:bean id="customAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased" >
<beans:property name="decisionVoters" >
		  <beans:bean class="org.springframework.security.access.vote.RoleVoter">
			<beans:property name="rolePrefix" value=""/>

Besides that point that we have protected a certain businessMethod, note that because we want to configure access without a prefix (ROLE_ by default), we have had to define a customAccessDecisionManager that in turn uses a RoleVoter that is configured for no prefix. (There is an attribute in the http element of the namespace for taking care of expressions called use-expressions=”true”; but on the method side of the fence, the namespace configuration does not offer any such convenience. Hence we have  to resort to a customAccessDecisionManager with a prefix-less roleVoter)


At a very high level we’ve seen what Spring Security namespaces do for us. We have visited the main classes involved with Spring Security, talked a little bit about the confusion (that at least I faced) regarding GROUPS, AUTHORITIES and ROLES. We’ve gone through the steps that Authentication and Authorization entail. Lastly we looked at how to secure URLs and Service methods.

As with anything Spring, Spring Security is a highly configurable framework and the more we know the internals of the various classes, the more we can customize for our circumstances.

If you like what you read, share what you like!
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • RSS
  • Technorati
  • DZone
  1. May 21st, 2012 at 02:11 | #1

    Some tips i have seen in terms of computer memory is the fact there are specs such as SDRAM, DDR and the like, that must match up the specifications of the motherboard. If the personal computer’s motherboard is very current while there are no main system issues, changing the memory space literally normally takes under a couple of hours. It’s one of the easiest pc upgrade processes one can visualize. Thanks for spreading your ideas.

  1. No trackbacks yet.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes