Friday, March 5, 2010

Spring Security - A peak under the hood

When I was introduced to spring security last year, I wanted to know what's going on under-the-hood. So I went to the best source to get the information I needed - The Source code. While I did my follow through, run-time step through of the framework, I made notes partially in my notebook and partially in my head (not ideal I know). However this knowledge has helped me do some customisation I'm currently working on and thought I should do a brain (and notepad) dump so that I can come back to this if needed again. So here goes..

Basics on configuring spring security
Configuring spring security for a web-application;
- Add the DelegatingFilterProxy filter in your web.xml
Configure this filter with a filter name 'springSecurityFilterChain'. Reason for this is discussed briefly later in this rant.
- Enable the filter for all requests. You can choose certain url patterns not to go through the filter.
Even if you don't do this, the spring security configuration allows skipping security certain url patterns.
- Create a separate spring configuration which holds all the security configurations.
It's cleaner and easier to maintain the security configurations if its kept separate.
- Make sure the spring security configuration is loaded as part of the context.
- Configure the spring security configuration to suite your requirements
At this point I'm going to leave the configuration details out of this notes. Instead we take a turn towards some of the internals on what goes under the hood of the framework.

The gist of it
The concept of the framework is to;
Define a set of roles(or authorities),
Define a set of resources (in the form of url patterns) and
Apply restrictions to the resources based on the permissions defined. The permissions are based on the roles(or authorities) applicable to a particular user and whether those roles(or authorities) have access to a resource or not.
This could be thought of as a 50k foot view on what spring security provides. Obviously there's much more that the framework provides. But I'd like to think that this is the gist of it.
Now getting onto a bit of details...

Some analogy to start off
At the core of Spring security, servlet filters and the HttpSession is employed to work it's magic. If accessing a secured web resource is analogous to going into a secured room of a building through few doors and coming back to the starting point through the same route, then the filters would be the doors. And there will be some action performed going through and coming out of each of these doors. These actions would remember what happened through these doors by holding it in some sort of a log record - this would be the HttpSession. Finally a check is done if the user is allowed to get in or not and sends the user back on the same route with a success or failure response.
Hence IMHO I believe to understand what spring security does, its useful to know what these filters are, how and what they do.

What's the DelegatingFilterProxy
The entry point to the spring security framework starts from one filter - DelegatingFilterProxy. The filter it self doesn't have a lot going on. As the name describes it, it's just a 'delegating' filter. It initializes looking for a target bean to delegate the filter chain. DelegatingFilterProxy, supports a init-param called 'targetBeanName'. This defines what bean it should delegate to. This is of course optional to configure. By default it would use the filter-name given in the filter config for this filter. And internally it delegates to the 'FilterProxyChain' filter. It finds the 'FilterProxyChain' by means of the filter name and that would need to be 'springSecurityFilterChain'. Once the delegator is worked out, the delegation happens..

What happens when the delegation begins
The FilterChainProxy gets to work when the delegation begins. It uses a pre-initialised map which holds information about a bunch of filters to execute. The filter chain continues invoking all filters defined in the map. Spring security has a pre-defined set of filters registered for the chain by default. This can be changed if needed. However if the default is accepted, the following filters will be in the chain of execution;

  • FilterChainProxy
  • SecurityContextPersistenceFilter
  • SecurityContextHolderAwareRequestFilter
  • ExceptionTranslationFilter
  • ChannelProcessingFilter
So the obvious curiosity at this point would be to know who/what initialises this map of default list of filters. The answer lies in the HttpSecurityBeanDefinitionParser.parse(Element element, ParserContext parserContext) method. This is part of the spring security configuration components. This rather long method registering the above filters (including the FilterProxyChain filter).
Now that the FilterProxyChain has kicked off the chain, each filter performs their responsibilities. The internals of all these filters are best understood by looking at them. However there's one particular filter worth discussing - SecurityContextPersistenceFilter. This filter has a special place in the framework. Before diving into this filter though there's a more important component to pay attention to, which is the SecurityContext.

What is the SecurityContext
The SecurityContext is a simple yet powerful interface that provides a mechanism to store and access Authenticaiton details during a executing thread. Spring security populates and depends on the SecurityContext at its core. When a person is authenticated their authentication details are held in the SecurityContext. The simple interface sets and returns an Authentication instance which extends the characteristics of java security's Pricipal. The application can decide what gets stored in the Authentication instance.
An explanation of the SecurityContext cannot be completed without the mention of the SecurityContextHolder.
As the definition states, SecurityContext presents minimum security information associated with the current thread of execution. The minimum security information is presented by the Authenticaion object it exposes as discussed above. The SecurityContextHolder holds the responsibility of attaching a SecurityContext with the current thread of execution. It does this by employing the ThreadLocal. The SecurityContext provides (as of the time of writing) 3 modes/strategies to attach a SecurityContext to the current thread of execution.
  • ThreadLocal
  • InheritableThreadLocal
  • Global
ThreadLocal; as it suggests implements a standard ThreadLocal implementation of the JDK. ThreadLocalSecurityContextHolderStrategy demonstrates a standard ThreadLocal implementation and holds the SecurityContext in the current thread. This is also the default strategy used if none is explicitly provided.
InheritableThreadLocal; as the API defines it, is a inheritable implementation (InheritableThreadLocalSecurityContextHolderStrategy) of the ThreadLocal. Provides sharing and overriding values between parent and child threads where applicable.
Global; Is a static field based implementation (GlobalSecurityContextHolderStrategy). Hence the SecurityContext held on this strategy is shared by all instances on the jvm. As the code documentation states, this is generally used for rich client applications.
The SecurityContextHolder employs one of this strategies to attach the SecurityContext onto the thread. It provides an API to create, store and clean-up the SecurityContext for any of these strategies used. And the strategy employed is always initialised once (with the exception of some one explicitly setting the strategy) for the jvm.
Now that the SecurityContext is dealt with, we shift attention back to the SecurityContextPeristenceFilter.

Back to the SecurityContextPersistenceFilter
As discussed above, this filter is invoked in the filter chain process and more importantly is the first as well. It's important that this is invoked as this sets up the core needed for others to do their work. This filter makes sure the SecurityContextHolder has the SecurityContext to be attached to the thread.
It also uses the HttpSession (via a HttpSessionSecurityContextRepository) to hold the SecurityContext within the user's HttpSession, so that the SecurityContext can be shared between requests. The repository implementation that manipulates the session creates a session if a current session does not exist based on the configuration attribute 'allowSessionCreation'. This by default is true. As a result you might end up with a lot of HttpSession objects within your heap. This usually is not a problem. But if heap space is of concern then you might want to consider turning off the new session creation option by setting 'allowSessionCreation' to 'false'. However this opens up several other impacts and one would have to ensure that anyone using the SecurityContextHolder should not depend on the SecurityContext being persisted between web-requests. However applicatoins need to ensure that the minimum data is held in the Authentication instances so that the session wont get too heavy.
So this filter focuses on persisting the SecurityContext through the SecurityContextHolder for rest of the filters/components to do their work. One might raise a concern on the approach of storing these values in the HttpSession and thread-local. As discussed above, choosing not to store it in the HttpSession is an option, but one that should be used cautiously. As for the ThreadLocal, concerns would pile up on situations where thread pools are employed to serve web requests in an application server and the cleansing of these ThreadLocals. Spring security takes care of this by ensuring that TheadLocals are only used in the life time of the thread serving a request. The populated ThreadLocal is cleaned up before the thread returns to the pool.
So, one-by-one in the chain, these filters perform their duties to enforce security for the application. Understanding these filters makes it easy to trace down problems and provide your own extensions. May the source be with you!!!