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:
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 3.0 and 3.1 require at least JDK 1.5 and also require Spring 3.0.3 as a minimum. Ideally you should be using the latest release versions to avoid problems. 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. | |
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. |
1. Authentication | |
1.1. | When I try to log in, I get an error message that says "Bad Credentials". What's wrong? |
This means that authentication has failed. It doesn't say why, as it is good practice to avoid giving details which might help an attacker guess account names or passwords. This also means that if you ask this question in the forum, you will
not get an answer unless you provide additional information. As with any
issue you should check the output from the debug log, note any exception
stacktraces and related messages. Step through the code in a debugger to
see where the authentication fails and why. Write a test case which
exercises your authentication configuration outside of the application.
More often than not, the failure is due to a difference in the password
data stored in a database and that entered by the user. If you are using
hashed passwords, make sure the value stored in your database is
exactly the same as the value produced by the
| |
1.2. | 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. | |
1.3. | 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. | |
1.4. | 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
| |
1.5. | 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 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. | |
1.6. | I can't get LDAP authentication to work. What's wrong with my configuration? |
Note that the permissions for an LDAP directory often do not allow you to read the password
for a user. Hence it is often not possible to use the The most common problem with LDAP authentication is a lack of knowledge of the directory server tree structure and configuration. This will be different in different companies, so you have to find it out yourself. Before adding a Spring Security LDAP configuration to an application, it's a good idea to write a simple test using standard Java LDAP code (without Spring Security involved), and make sure you can get that to work first. For example, to authenticate a user, you could use the following code: @Test public void ldapAuthenticationIsSuccessful() throws Exception { Hashtable<String,String> env = new Hashtable<String,String>(); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "cn=joe,ou=users,dc=mycompany,dc=com"); env.put(Context.PROVIDER_URL, "ldap://mycompany.com:389/dc=mycompany,dc=com"); env.put(Context.SECURITY_CREDENTIALS, "joespassword"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialLdapContext ctx = new InitialLdapContext(env, null); }
| |
2. Session Management | |
Session management issues are a common source of forum questions. If you are developing Java web applications, you should understand how the session is maintained between the servlet container and the user's browser. You should also understand the difference between secure and non-secure cookies and the implications of using HTTP/HTTPS and switching between the two. Spring Security has nothing to do with maintaining the session or providing session identifiers. This is entirely handled by the servlet container. | |
2.1. | I'm using Spring Security's concurrent session control to prevent users from logging in more than once at a time. When I open another browser window after logging in, it doesn't stop me from logging in again. Why can I log in more than once? |
Browsers generally maintain a single session per browser instance. You cannot have two separate sessions at once. So if you log in again in another window or tab you are just reauthenticating in the same session. The server doesn't know anything about tabs, windows or browser instances. All it sees are HTTP requests and it ties those to a particular session according to the value of the the JSESSIONID cookie that they contain. When a user authenticates during a session, Spring Security's concurrent session control checks the number of other authenticated sessions that they have. If they are already authenticated with the same session, then re-authenticating will have no effect. | |
2.2. | Why does the session Id change when I authenticate through Spring Security? |
With the default configuration, Spring Security invalidates the existing session when the user authenticates and creates a new one, transferring the session data to it. The intention is to change the session identifier to prevent “session-fixation” attacks. You can find more about this online and in the reference manual. | |
2.3. | I'm using Tomcat (or some other servlet container) 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 sessions created under HTTPS, for which the session cookie is marked as “secure”, cannot subsequently be used under HTTP. The browser will not send the cookie back to the server and any session state will be lost (including the security context information). Starting a session in HTTP first should work as the session cookie won't be marked as secure (you will also have to disable Spring Security's Session Fixation Protection support to prevent it from creating a new secure session on login (you can always create a new session yourself at a later stage). Note that switching between HTTP and HTTPS is not a good idea in general, as any application which uses HTTP at all is vulnerable to man-in-the-middle attacks. To be truly secure, the user should begin accessing your site in HTTPS and continue using it until they log out. Even clicking on an HTTPS link from a page accessed over HTTP is potentially risky. If you need more convincing, check out a tool like sslstrip. | |
2.4. | I'm not switching between HTTP and HTTPS but my session is still getting lost |
Sessions are maintained either by exchanging a session cookie or by
adding the a | |
2.5. | 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.6. | Spring Security is creating a session somewhere, even though I've
configured it not to, by setting the |
This usually means that the user's application is creating a session
somewhere, but that they aren't aware of it. The most common culprit is
a JSP. Many people aren't aware that JSPs create sessions by default. To
prevent a JSP from creating a session, add the directive If you are having trouble working out where a session is being
created, you can add some debugging code to track down the location(s).
One way to do this would be to add a
| |
3. Miscellaneous | |
3.1. | 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>. | |
3.2. | 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. |
In a Spring web application, the application context which holds the
Spring MVC beans for the dispatcher servlet is often separate from the
main application context. It is often defined in a file called
Generally we would recommend applying method security at the service layer rather than on individual web controllers. | |
3.3. | I have a user who has definitely been authenticated, but when I try to
access the |
If you have excluded the request from the security filter chain using
the attribute |
1.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 easier and allows you to troubleshoot exceptions by looking directly at the code where they occur to see what's going on there. | |
1.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. There is also a
detailed blog article called “Behind the Spring Security
Namespace” on blog.springsource.com. If want to know the full details then the
code is in the | |
1.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
The prefix can be changed by setting the
| |
1.4. | 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
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. The reference manual also includes an appendix listing the first-level dependencies for each Spring Security module with some information on whether they are optional and what they are required for. 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. | |
1.5. | What dependencies are needed to run an embedded ApacheDS LDAP server? |
If you are using Maven, you need to add the folowing to your pom dependencies: <dependency> <groupId>org.apache.directory.server</groupId> <artifactId>apacheds-core</artifactId> <version>1.5.5</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.directory.server</groupId> <artifactId>apacheds-server-jndi</artifactId> <version>1.5.5</version> <scope>runtime</scope> </dependency> . The other required jars should be pulled in transitively. | |
1.6. | What is a |
If you want to customize the authentication process then you should
implement |
1.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
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 | |
1.2. | How do I apply different |
You can't do this, since the fragment is not transmitted from the browser to the server. The URLs above are identical from the server's perspective. This is a common question from GWT users. | |
1.3. | How do I access the user's IP Address (or other web-request data) in a
|
Obviously you can't (without resorting to something like thread-local
variables) since the only information supplied to the interface is the
username. Instead of implementing
In a standard web setup, the | |
1.4. | How do I access the |
You can't, since the If you really need to access the session, then it must be done by customizing the web tier. | |
1.5. | How do I access the user's password in a
|
You can't (and shouldn't). You are probably misunderstanding its purpose. See “What is a UserDetailsService?” above. | |
1.6. | 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
To load the data from an alternative source, you must be using an
explicitly declared security filter chain (typically Spring Security's
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
| |
1.7. | How do I authenticate against LDAP but load user roles from a database? |
The 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 | |
1.8. | I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it. What can I do short of abandoning namespace use? |
The namespace functionality is intentionally limited, so it doesn't
cover everything that you can do with plain beans. If you want to do
something simple, like modify a bean, or inject a different dependency,
you can do this by adding a
Normally, you would add the functionality you require to the
public class BeanPostProcessor implements BeanPostProcessor { public Object postProcessAfterInitialization(Object bean, String name) { if (bean instanceof UsernamePasswordAuthenticationFilter) { System.out.println("********* Post-processing " + name); ((UsernamePasswordAuthenticationFilter)bean).setAuthenticationDetailsSource( new AuthenticationDetailsSource() { public Object buildDetails(Object context) { return ((HttpServletRequest)context).getHeader("CUSTOM_HEADER"); } }); } return bean; } public Object postProcessBeforeInitialization(Object bean, String name) { return bean; } } You would then register this bean in your application context. Spring will automatically invoke it on the beans defined in the application context. |
[1] 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.