Frequently Answered Questions (FAQ)


1. General
1.1. Will Spring Security take care of all my application security requirements?
1.2. Why not just use web.xml security?
1.3. What Java and Spring Framework versions are required?
1.4. I'm new to Spring Security and I need to build an application that supports CAS single sign-on over HTTPS, while allowing Basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). I've copied some configuration files I found but it doesn't work. What could be wrong?
2. Common Problems
2.1. My application goes into an "endless loop" when I try to login, what's going on?
2.2. I get an exception with the message "Access is denied (user is anonymous);". What's wrong?
2.3. Why can I still see a secured page even after I've logged out of my application?
2.4. I get an exception with the message "An Authentication object was not found in the SecurityContext". What's wrong?
2.5. I'm using Tomcat and have enabled HTTPS for my login page, switching back to HTTP afterwards. It doesn't work - I just end up back at the login page after authenticating.
2.6. I'm forwarding a request to another URL using the RequestDispatcher, but my security constraints aren't being applied.
2.7. I'm trying to use the concurrent session-control support but it won't let me log back in, even if I'm sure I've logged out and haven't exceeded the allowed sessions.
2.8. I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null. Why can't I see the user information?
2.9. I have added Spring Security's <global-method-security> element to my application context but if I add security annotations to my Spring MVC controller beans (Struts actions etc.) then they don't seem to have an effect.
3. Spring Security Architecture Questions
3.1. How do I know which package class X is in?
3.2. How do the namespace elements map to conventional bean configurations?
3.3. What does “ROLE_” mean and why do I need it on my role names?
4. Common Howto Requests
4.1. I need to login in with more information than just the username. How do I add support for extra login fields (e.g. a company name)?
4.2. How do I define the secured URLs within an application dynamically?
4.3. How do I know which dependencies to add to my application to work with Spring Security?
4.4. How do I authenticate against LDAP but load user roles from a database?

1. General

1.1. Will Spring Security take care of all my application security requirements?
1.2. Why not just use web.xml security?
1.3. What Java and Spring Framework versions are required?
1.4. I'm new to Spring Security and I need to build an application that supports CAS single sign-on over HTTPS, while allowing Basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). I've copied some configuration files I found but it doesn't work. What could be wrong?

1.1.

Will Spring Security take care of all my application security requirements?

Spring Security provides you with a very flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope. Web applications are vulnerable to all kinds of attacks which you should be familiar with, preferably before you start development so you can design and code with them in mind from the beginning. Check out the OWASP web site for information on the major issues facing web application developers and the countermeasures you can use against them.

1.2.

Why not just use web.xml security?

Let's assume you're developing an enterprise application based on Spring. There are four security concerns you typically need to address: authentication, web request security, service layer security (i.e. your methods that implement business logic), and domain object instance security (i.e. different domain objects have different permissions). With these typical requirements in mind:

  1. Authentication: The servlet specification provides an approach to authentication. However, you will need to configure the container to perform authentication which typically requires editing of container-specific "realm" settings. This makes a non-portable configuration, and if you need to write an actual Java class to implement the container's authentication interface, it becomes even more non-portable. With Spring Security you achieve complete portability - right down to the WAR level. Also, Spring Security offers a choice of production-proven authentication providers and mechanisms, meaning you can switch your authentication approaches at deployment time. This is particularly valuable for software vendors writing products that need to work in an unknown target environment.

  2. Web request security: The servlet specification provides an approach to secure your request URIs. However, these URIs can only be expressed in the servlet specification's own limited URI path format. Spring Security provides a far more comprehensive approach. For instance, you can use Ant paths or regular expressions, you can consider parts of the URI other than simply the requested page (e.g. you can consider HTTP GET parameters) and you can implement your own runtime source of configuration data. This means your web request security can be dynamically changed during the actual execution of your webapp.

  3. Service layer and domain object security: The absence of support in the servlet specification for services layer security or domain object instance security represent serious limitations for multi-tiered applications. Typically developers either ignore these requirements, or implement security logic within their MVC controller code (or even worse, inside the views). There are serious disadvantages with this approach:

    1. Separation of concerns: Authorization is a crosscutting concern and should be implemented as such. MVC controllers or views implementing authorization code makes it more difficult to test both the controller and authorization logic, more difficult to debug, and will often lead to code duplication.

    2. Support for rich clients and web services: If an additional client type must ultimately be supported, any authorization code embedded within the web layer is non-reusable. It should be considered that Spring remoting exporters only export service layer beans (not MVC controllers). As such authorization logic needs to be located in the services layer to support a multitude of client types.

    3. Layering issues: An MVC controller or view is simply the incorrect architectural layer to implement authorization decisions concerning services layer methods or domain object instances. Whilst the Principal may be passed to the services layer to enable it to make the authorization decision, doing so would introduce an additional argument on every services layer method. A more elegant approach is to use a ThreadLocal to hold the Principal, although this would likely increase development time to a point where it would become more economical (on a cost-benefit basis) to simply use a dedicated security framework.

    4. Authorisation code quality: It is often said of web frameworks that they "make it easier to do the right things, and harder to do the wrong things". Security frameworks are the same, because they are designed in an abstract manner for a wide range of purposes. Writing your own authorization code from scratch does not provide the "design check" a framework would offer, and in-house authorization code will typically lack the improvements that emerge from widespread deployment, peer review and new versions.

For simple applications, servlet specification security may just be enough. Although when considered within the context of web container portability, configuration requirements, limited web request security flexibility, and non-existent services layer and domain object instance security, it becomes clear why developers often look to alternative solutions.

1.3.

What Java and Spring Framework versions are required?

Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built against Spring 2.0.x. It should also be compatible with applications using Spring 2.5.x.

Spring Security 3.0 requires JDK 1.5 as a minimum and will also require Spring 3.0.

1.4.

I'm new to Spring Security and I need to build an application that supports CAS single sign-on over HTTPS, while allowing Basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). I've copied some configuration files I found but it doesn't work. What could be wrong?

Or subsititute an alternative complex scenario...

Realistically, you need an understanding of the technolgies you are intending to use before you can successfully build applications with them. Security is complicated. Setting up a simple configuration using a login form and some hard-coded users using Spring Security's namespace is reasonably straightforward. Moving to using a backed JDBC database is also easy enough. But if you try and jump straight to a complicated deployment scenario like this you will almost certainly be frustrated. There is a big jump in the learning curve required to set up systems like CAS, configure LDAP servers and install SSL certificates properly. So you need to take things one step at a time.

From a Spring Security perspective, the first thing you should do is follow the Getting Started guide on the web site. This will take you through a series of steps to get up and running and get some idea of how the framework operates. If you are using other technologies which you aren't familiar with then you should do some research and try to make sure you can use them in isolation before combining them in a complex system.

2. Common Problems

2.1. My application goes into an "endless loop" when I try to login, what's going on?
2.2. I get an exception with the message "Access is denied (user is anonymous);". What's wrong?
2.3. Why can I still see a secured page even after I've logged out of my application?
2.4. I get an exception with the message "An Authentication object was not found in the SecurityContext". What's wrong?
2.5. I'm using Tomcat and have enabled HTTPS for my login page, switching back to HTTP afterwards. It doesn't work - I just end up back at the login page after authenticating.
2.6. I'm forwarding a request to another URL using the RequestDispatcher, but my security constraints aren't being applied.
2.7. I'm trying to use the concurrent session-control support but it won't let me log back in, even if I'm sure I've logged out and haven't exceeded the allowed sessions.
2.8. I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null. Why can't I see the user information?
2.9. I have added Spring Security's <global-method-security> element to my application context but if I add security annotations to my Spring MVC controller beans (Struts actions etc.) then they don't seem to have an effect.

2.1.

My application goes into an "endless loop" when I try to login, what's going on?

A common user problem with infinite loop and redirecting to the login page is caused by accidently configuring the login page as a "secured" resource. Make sure your configuration allows anonymous access to the login page, either by excluding it from the security filter chain or marking it as requiring ROLE_ANONYMOUS.

If your AccessDecisionManager includes an AuthenticatedVoter, you can use the attribute "IS_AUTHENTICATED_ANONYMOUSLY". This is automatically available if you are using the standard namespace configuration setup.

From Spring Security 2.0.1 onwards, when you are using namespace-based configuration, a check will be made on loading the application context and a warning message logged if your login page appears to be protected.

2.2.

I get an exception with the message "Access is denied (user is anonymous);". What's wrong?

This is a debug level message which occurs the first time an anonymous user attempts to access a protected resource.

    DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point
    org.springframework.security.AccessDeniedException: Access is denied
    at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68)
    at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262)
                

It is normal and shouldn't be anything to worry about.

2.3.

Why can I still see a secured page even after I've logged out of my application?

The most common reason for this is that your browser has cached the page and you are seeing a copy which is being retrieved from the browsers cache. Verify this by checking whether the browser is actually sending the request (check your server access logs, the debug log or use a suitable browser debugging plugin such as Tamper Data for Firefox). This has nothing to do with Spring Security and you should configure your application or server to set the appropriate Cache-Control response headers. Note that SSL requests are never cached.

2.4.

I get an exception with the message "An Authentication object was not found in the SecurityContext". What's wrong?

This is a another debug level message which occurs the first time an anonymous user attempts to access a protected resource, but when you do not have an AnonymousAuthenticationFilter in your filter chain configuration.

    DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point
    org.springframework.security.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
    at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
                

It is normal and shouldn't be anything to worry about.

2.5.

I'm using Tomcat and have enabled HTTPS for my login page, switching back to HTTP afterwards. It doesn't work - I just end up back at the login page after authenticating.

This happens because Tomcat sessions created under HTTPS cannot subsequently be used under HTTP and any session state is lost (including the security context information). Starting a session in HTTP first should work as the session cookie won't be marked as secure.

2.6.

I'm forwarding a request to another URL using the RequestDispatcher, but my security constraints aren't being applied.

Filters are not applied by default to forwards or includes. If you really want the security filters to be applied to forwards and/or includes, then you have to configure these explicitly in your web.xml using the <dispatcher> element, a child element of <filter-mapping>.

2.7.

I'm trying to use the concurrent session-control support but it won't let me log back in, even if I'm sure I've logged out and haven't exceeded the allowed sessions.

Make sure you have added the listener to your web.xml file. It is essential to make sure that the Spring Security session registry is notified when a session is destroyed. Without it, the session information will not be removed from the registry.

    <listener>
        <listener-class>org.springframework.security.ui.session.HttpSessionEventPublisher</listener-class>
    </listener> 
            

2.8.

I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null. Why can't I see the user information?

If you have excluded the request from the security filter chain using the attribute filters='none' in the <intercept-url> element that matches the URL pattern, then the SecurityContextHolder will not be populated for that request. Check the debug log to see whether the request is passing through the filter chain. (You are reading the debug log, right?).

2.9.

I have added Spring Security's <global-method-security> element to my application context but if I add security annotations to my Spring MVC controller beans (Struts actions etc.) then they don't seem to have an effect.

The application context which holds the Spring MVC beans for the dispatcher servlet is a child application context of the main application context which is loaded using the ContextLoaderListener you define in your web.xml. The beans in the child context are not visible in the parent context so you need to either move the <global-method-security> declaration to the web context or moved the beans you want secured into the main application context.

Generally we would recommend applying method security at the service layer rather than on individual web controllers.

3. Spring Security Architecture Questions

3.1. How do I know which package class X is in?
3.2. How do the namespace elements map to conventional bean configurations?
3.3. What does “ROLE_” mean and why do I need it on my role names?

3.1.

How do I know which package class X is in?

The best way of locating classes is by installing the Spring Security source in your IDE. The distribution includes source jars for each of the modules the project is divided up into. Add these to your project source path and you can navigate directly to Spring Security classes (Ctrl-Shift-T in Eclipse). This also makes debugging easer and allows you to troubleshoot exceptions by looking directly at the code where they occur to see what's going on there.

3.2.

How do the namespace elements map to conventional bean configurations?

There is a general overview of what beans are created by the namespace in the namespace appendix of the reference guide. If want to know the full details then the code is in the spring-security-config module within the Spring Security 3.0 distribution. You should probably read the chapters on namespace parsing in the standard Spring Framework reference documentation first.

3.3.

What does ROLE_ mean and why do I need it on my role names?

Spring Security has a voter-based architecture which means that an access decision is made by a series of AccessDecisionVoters. The voters act on the configuration attributes which are specified for a secured resource (such as a method invocation). With this approach, not all attributes may be relevant to all voters and a voter needs to know when it should ignore an attribute (abstain) and when it should vote to grant or deny access based on the attribute value. The most common voter is the RoleVoter which by default votes whenever it finds an attribute with the ROLE_ prefix. It makes a simple comparison of the attribute (such as ROLE_USER) with the name names of the authorities which the current user has been assigned. If it finds a match (they have an authority called ROLE_USER), it votes to grant access, otherwise it votes to deny access.

The prefix can be changed by setting the rolePrefix property of RoleVoter. If you only need to use roles in your application and have no need for other custom voters, then you can set the prefix to a blank string, in which case the RoleVoter will treat all attributes as roles.

4. Common Howto Requests

4.1. I need to login in with more information than just the username. How do I add support for extra login fields (e.g. a company name)?
4.2. How do I define the secured URLs within an application dynamically?
4.3. How do I know which dependencies to add to my application to work with Spring Security?
4.4. How do I authenticate against LDAP but load user roles from a database?

4.1.

I need to login in with more information than just the username. How do I add support for extra login fields (e.g. a company name)?

This question comes up repeatedly in the Spring Security forum so you will find more information there by searching the archives (or through google).

The submitted login information is processed by an instance of UsernamePasswordAuthenticationFilter. You will need to customize this class to handle the extra data field(s). One option is to use your own customized authentication token class (rather than the standard UsernamePasswordAuthenticationToken), another is simply to concatenate the extra fields with the username (for example, using a ":" as the separator) and pass them in the username property of UsernamePasswordAuthenticationToken.

You will also need to customize the actual authentication process. If you are using a custom authentication token class, for example, you will have to write an AuthenticationProvider to handle it (or extend the standard DaoAuthenticationProvider). If you have concatenated the fields, you can implement your own UserDetailsService which splits them up and loads the appropriate user data for authentication.

4.2.

How do I define the secured URLs within an application dynamically?

People often ask about how to store the mapping between secured URLs and security metadata attributes in a database, rather than in the application context.

The first thing you should ask yourself is if you really need to do this. If an application requires securing, then it also requires that the security be tested thoroughly based on a defined policy. It may require auditing and acceptance testing before being rolled out into a production environment. A security-conscious organization should be aware that the benefits of their diligent testing process could be wiped out instantly by allowing the security settings to be modified at runtime by changing a row or two in a configuration database. If you have taken this into account (perhaps using multiple layers of security within your application) then Spring Security allows you to fully customize the source of security metadata. You can make it fully dynamic if you choose.

Both method and web security are protected by subclasses of AbstractSecurityInterceptor which is configured with a SecurityMetadataSource from which it obtains the metadata for a particular method or filter invocation [1]. For web security, the interceptor class is FilterSecurityInterceptor and it uses the marker interface FilterInvocationSecurityMetadataSource. The secured object type it operates on is a FilterInvocation. The default implementation which is used (both in the namespace <http> and when configuring the interceptor explicitly, stores the list of URL patterns and their corresponding list of configuration attributes (instances of ConfigAttribute) in an in-memory map.

To load the data from an alternative source, you must be using an explicitly declared security filter chain (typically Spring Security's FilterChainProxy) in order to customize the FilterSecurityInterceptor bean. You can't use the namespace. You would then implement FilterInvocationSecurityMetadataSource to load the data as you please for a particular FilterInvocation[2]. A very basic outline would look something like this:

  public class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    public List<ConfigAttribute> getAttributes(Object object) {
      FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();
        String httpMethod = fi.getRequest().getMethod();
        List<ConfigAttribute> attributes = new ArrayList<ConfigAttribute>();

        // Lookup your database (or other source) using this information and populate the
        // list of attributes

        return attributes;
    }

    public Collection<ConfigAttribute> getAllConfigAttributes() {
      return null;
    }

    public boolean supports(Class<?> clazz) {
      return FilterInvocation.class.isAssignableFrom(clazz);
    }
  }
  

For more information, look at the code for DefaultFilterInvocationSecurityMetadataSource.

4.3.

How do I know which dependencies to add to my application to work with Spring Security?

It will depend on what features you are using and what type of application you are developing. With Spring Security 3.0, the project jars are divided into clearly distinct areas of functionality, so it is straightforward to work out which Spring Security jars you need from your application requirements. All applications will need the spring-security-core jar. If you're developing a web application, you need the spring-security-web jar. If you're using security namespace configuration you need the spring-security-config jar, for LDAP support you need the spring-security-ldap jar and so on.

For third-party jars the situation isn't always quite so obvious. A good starting point is to copy those from one of the pre-built sample applications WEB-INF/lib directories. For a basic application, you can start with the tutorial sample. If you want to use LDAP, with an embedded test server, then use the LDAP sample as a starting point.

If you are building your project with maven, then adding the appropriate Spring Security modules as dependencies to your pom.xml will automatically pull in the core jars that the framework requires. Any which are marked as "optional" in the Spring Security POM files will have to be added to your own pom.xml file if you need them.

4.4.

How do I authenticate against LDAP but load user roles from a database?

The LdapAuthenticationProvider bean (which handles normal LDAP authentication in Spring Security) is configured with two separate strategy interfaces, one which performs the authenticatation and one which loads the user authorities, called LdapAuthenticator and LdapAuthoritiesPopulator respectively. The DefaultLdapAuthoritiesPopulator loads the user authorities from the LDAP directory and has various configuration parameters to allow you to specify how these should be retrieved.

To use JDBC instead, you can implement the interface yourself, using whatever SQL is appropriate for your schema:

  public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {
    @Autowired
    JdbcTemplate template;

    List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
      List<GrantedAuthority> = template.query("select role from roles where username = ?", new String[] {username}, new RowMapper<GrantedAuthority>() {
        /**
         *  We're assuming here that you're using the standard convention of using the role
         *  prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter.
         */
        public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
          return new GrantedAuthorityImpl("ROLE_" + rs.getString(1);
        }
      }
    }
  }
  

You would then add a bean of this type to your application context and inject it into the LdapAuthenticationProvider. This is covered in the section on configuring LDAP using explicit Spring beans in the LDAP chapter of the reference manual. Note that you can't use the namespace for configuration in this case. You should also consult the Javadoc for the relevant classes and interfaces.



[1] This class previouly went by the rather obscure name of ObjectDefinitionSource, but has been renamed in Spring Security 3.0

[2] The FilterInvocation object contains the HttpServletRequest, so you can obtain the URL or any other relevant information on which to base your decision on what the list of returned attributes will contain.