Jul 07

5 Minute Guide to Spring Security

Tag: acegi,development,java,security,springpmularien @ 9:02 pm

Update! May 31, 2010: I have published a new book, Spring Security 3, covering many aspects of Spring Security from top to bottom. The book is targeted both at novices and intermediate to advanced users. I’d encourage you to read my blog post of the announcement, and visit the book’s web site, to determine if you think it will help you.

Although I’ve used Acegi Security in the past, I hadn’t tried it since it was renamed Spring Security and folded into the Spring Portfolio. I decided to approach its integration into a typical Spring web application with the eyes of a new user and write up my notes as a 5 minute guide to Spring Security.

Pretending to be a new user, I found the suggested steps a bit bewildering. Let’s take these one at a time, and I’ll try to help you out where the instructions are unclear:

1. First of all, deploy the “Tutorial Sample”, which is included in the main distribution ZIP file.

Aside from the weird packaging of Spring Security, it’s not clear which file this is. You should be deploying spring-security-samples-tutorial-2.0.x.war to your servlet container in the usual fashion. In the case of Tomcat, for example, use the deployment tool or drop this into your webapps directory. You should see the tutorial application in your browser. Let’s move to step 2…

2. Next, follow the Petclinic Tutorial , which covers how to add Spring Security to the commonly-used Petclinic sample application that ships with Spring.

This is pretty straightforward. The only error I found was that there is a reference to %spring-sec-tutorial%\WEB-INF\applicationContext-security-ns.xml. This should be applicationContext-security.xml instead. Note that I didn’t actually try this part of the tutorial with the Petclinic application, since I had my own test app I wanted to integrate with.

And here’s where the fun starts. Once you get past the convention over configuration convenience, you will need to customize Spring Security. One of the first things I looked for in the documentation was what all the bits in the XML namespace did. When this product was Acegi security, you could be pretty sure of looking at the Javadoc and getting documentation. Not so with XML configuration! While the Spring Framework documentation includes an excellent appendix with a reasonable level of detail on each of the namespaced XML declarations, Spring Security has nothing like this.

With convention over configuration, good documentation of the defaults becomes especially important, and it’s unfortunate the documentation isn’t really adequate in this area.

That said, I’ll try to cover a basic scenario here where we integrate Spring Security, using database-backed authentication, into an existing Spring web application. Here’s what I wanted for my example:

  • Database-backed authentication
  • Users have a single “role” – either plain user, or admin
  • Customized login page

It’s a bit hard to cover this in 5 minutes, so I have skipped some of the stuff I hope you know already, such as use of Spring XML namespaces, and configuring simple JDBC DataSources. Please let me know if you miss this stuff! :)

Getting Started

I would suggest getting started with the applicationContext-security.xml that is found in the tutorial sample, and trimming it down a bit. Here’s what I got when I trimmed it down:

<?xml version="1.0" encoding="UTF-8"?>
  - Sample namespace-based configuration
  - $Id: applicationContext-security.xml 3019 2008-05-01 17:51:48Z luke_t $
<beans:beans xmlns="http://www.springframework.org/schema/security"
	<global-method-security secured-annotations="enabled">
    <http auto-config="true">
        <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    Usernames/Passwords are
        <password-encoder hash="md5"/>
            <user name="rod" password="a564de63c2d0da68cf47586ee05984d7" authorities="ROLE_SUPERVISOR, ROLE_USER, ROLE_TELLER" />
            <user name="dianne" password="65d15fe9156f9c4bbffd98085992a44e" authorities="ROLE_USER,ROLE_TELLER" />
            <user name="scott" password="2b58af6dddbd072ed27ffc86725d7d3a" authorities="ROLE_USER" />
            <user name="peter" password="22b5c9accc6e1ba628cedc63a72d57f8" authorities="ROLE_USER" />

This makes a good baseline for the modifications we’re going to make. But first…

Mapping XML Elements to Java Code

I found it very helpful at this point, before messing with the XML, to know where the Java code was that corresponded to the available XML elements. The basic class that Spring Security uses for mapping XML elements to beans is SecurityNamespaceHandler. The code in this class simply delegates XML elements to bean definition parsers. It’s easy to follow along and map XML elements to Java code in this way. Unfortunately, don’t expect extensive commenting in the Java code to help you :(

web.xml Changes

I agree with the Spring Security documentation and found it easier to extract the security-related stuff into its own XML configuration file. This allows you to play XML tricks and not require namespace-tagging for the security elements. First off, you have to include a reference to applicationContext-security.xml in your [Spring] initialization parameters in your web.xml file:


Next, as instructed by the Spring Security getting started guide, you need to add the filter mapping. In my case, this went right after the <context-param> end tag, since I didn’t have any other filters:


This default mapping will run all requests to your application through Spring Security. Now we’re done with web.xml, and we move on to…

Database-Backed Authentication

In my case, my application was already configured to use a JDBC DataSource, so pointing Spring Security at my JDBC data source was as easy as modifying the authentication-provider element to reference my already configured Spring bean:

	    <jdbc-user-service data-source-ref="dataSource"/>

Now, the immediate question I asked is – OK, what does the convention over configuration assume my database tables look like? If you look at the documentation of the JDBC authentication provider, you would expect to see that information there, but you’d be wrong.

Instead, you have to look at the SQL queries that are hard-coded in the JdbcDaoImpl class and infer the schema structure for yourself. This article has a graphical depiction of the basic schema down in section 5.4.

If you want to configure the queries that are used, simply match the available attributes on the jdbc-user-service element to the SQL queries in the Java class I referenced above. In my example, I wanted to simplify my schema by adding the user’s role directly to the user table. So I modified the XML configuration slightly as follows:

  <jdbc-user-service data-source-ref="dataSource" 
    authorities-by-username-query="select username,authority from users where username=?"/>

This allowed me to put values in the ‘authority’ column like ‘ROLE_ADMIN’ or ‘ROLE_USER’, which translate directly into Spring Security roles!

Configuring URL authorization

Mapping URLs to roles is really easy. In your http element, simply put successive elements like this:

        <intercept-url pattern="/admin/*.do" access="ROLE_ADMIN"  />
        <intercept-url pattern="/**.do" access="ROLE_USER,ROLE_ADMIN"  />

Note here that the ‘access’ attribute values directly correspond to the values returned by the second column of the authorities-by-username-query. The ‘.do’ mapping is what I arbitrarily chose for my application – you may have to adjust depending on what your application’s Spring-managed URLs look like.

Configuring and Branding Spring Security-managed Pages

Finally, I wanted to figure out where the pages related to Spring Security should be configured, so that I could modify them if I needed to. Somewhat oddly, Spring Security ships with a default login page whose HTML markup is located in a class file – DefaultLoginPageGeneratingFilter. We would (obviously) like to replace this with our own custom page. Since we are authenticating everything passing through the Spring servlet, we must use a JSP for this.

Add the following to the http tag in the security configuration file:

<form-login login-page="/login.jsp" />

Now you need to put the login.jsp page in your web application (generally in the WEB-INF directory). The basic structure of the page you’re creating will look like this:

<%@ page import="org.springframework.security.ui.webapp.AuthenticationProcessingFilter" %>
<%@ page import="org.springframework.security.ui.AbstractProcessingFilter" %>
<%@ page import="org.springframework.security.AuthenticationException" %>
<form action="j_spring_security_check">
	<label for="j_username">Username</label>
	<input type="text" name="j_username" id="j_username" <c:if test="${not empty param.login_error}">value='<%= session.getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY) %>'</c:if>/>
	<label for="j_password">Password</label>
	<input type="password" name="j_password" id="j_password"/>
	<input type='checkbox' name='_spring_security_remember_me'/> Remember me on this computer.
	<input type="submit" value="Login"/>

The names of the form elements and form action must match what is shown here otherwise your login form will not work!

Note also that this is a plain ol’ JSP page, and not under Spring control. It is likely that you could play with the servlet filter patterns in web.xml to bring these pages under Spring control, but that is a topic outside the scope of this brief tutorial.

There are a couple other pages you will want to configure.

Access Denied: This is the page the user will see if they are denied access to the site due to lack of authorization (i.e. tried to hit a page that they didn’t have access to hit, even though they were authenticated properly). This is configured as follows:

    <http ... access-denied-page="/accessDenied.jsp">

Default Target URL: This is where the user will be redirected upon successful login. This can (and probably should) be a page located under Spring control. Configured as follows:

    <http ... >
        <form-login ... default-target-url="/home.do"/>

Logout URL: The page where the user is redirected upon a successful logout. This can be a page located under Spring control too (provided that it allows anonymous access):

    <http ... >
    	<logout logout-success-url="/home.do"/>

Login Failure URL: Where the user will be sent if there was an authentication failure. Typically this is back to the login form, with a URL parameter, such as:

    <http ... >
        <form-login ... authentication-failure-url="/login.jsp?login_error=1"/>

Putting it Together

Here’s what my whole sample Spring security configuration looked like when I was done:

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">
	<global-method-security secured-annotations="enabled">
		<!-- AspectJ pointcut expression that locates our "post" method and applies security that way
		<protect-pointcut expression="execution(* bigbank.*Service.post*(..))" access="ROLE_TELLER"/>
    <http auto-config="true" access-denied-page="/accessDenied.jsp">
        <intercept-url pattern="/login.jsp*" filters="none"/>  
        <intercept-url pattern="/admin/editUser.do" access="ROLE_ADMIN"  />
        <intercept-url pattern="/admin/searchUsers.do" access="ROLE_ADMIN"  />
        <intercept-url pattern="/**.do" access="ROLE_USER,ROLE_ADMIN"  />
    	<form-login authentication-failure-url="/login.jsp?login_error=1" default-target-url="/home.do"/>
    	<logout logout-success-url="/home.do"/>
        <jdbc-user-service data-source-ref="dataSource" authorities-by-username-query="select username,authority from users where username=?"/>


Ironically, just as I was drafting this article, a smart colleague of mine happened to come to me telling me about all the problems he was having getting started with Spring Security. He complained about the lack of detailed documentation on the XML, and the fact that the getting started documentation really wasn’t comprehensive (both complains that I had as well). Note that this colleague also happened to be responsible for implementing Acegi Security with Spring in a prior project that we worked on together – so he was intimately familiar with the underlying technology. He ended up going back to the Java-based configuration mechanism in frustration!

Hope this helps you out and I always appreciate hearing your comments and questions.

Related Articles

95 Responses to “5 Minute Guide to Spring Security”

  1. sarada says:

    I am unable to import the files provided in the jsp page


    Could you please let me know which jar file i am missing.

  2. bayarja says:

    hi please i need to full source code. i don’t understand i hope you send me example.

  3. Naseer says:

    hi guys, i found this article very useful.. i really appreciate your effort. I sovled most of my issues related to spring security but i have few question todo.

    Here i have an application which is in struts and i injected spring security into it with different roles. now i am intercepting few url’s and delegating it to the appropraite action. but i want to intercept all the url and forward the control to struts-config to forward it to the appropriate action or jsp. please help me.


  4. Murali says:

    I would like to do form validation before the login check, if everything goes fine the actual login have to perform. how can i go ahead? can anyone help me?

  5. Eric Blue’s Blog » Weekly Lifestream for July 18th says:

    […] Shared » 5 Minute Guide to Spring Security – It’s Only Software. […]

  6. Sachin says:

    Sample application is not working for me, Tomcat log shows following error

    [ERROR,ContextLoader,http-8080-1] Context initialization failed
    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [applicationContext-business.xml]; nested exception is java.lang.IllegalArgumentException: Class [org.springframework.ejb.config.JeeNamespaceHandler] does not implement the NamespaceHandler interface
    Caused by: 
    java.lang.IllegalArgumentException: Class [org.springframework.ejb.config.JeeNamespaceHandler] does not implement the NamespaceHandler interface
  7. Vince says:

    I have a same problem as Murali, if I wanna make the struts validate before the login perform, how to archieve? I try to use redirect after post way but the j_username & j_password cannot be send through post method. Did anyone have solution for this?

  8. Fernando says:

    I am new to the spring security .
    I am trying to introduce spring security to my exiting web application. In the existing web application I am having authentication logic and once user authenticate I create HTTP Session and store user details .
    Now if I use spring –security as security authentication done by the spring framework where can I create HTTP Session and store my data?

  9. mulki moies hussain says:

    very nice explanation , thank you , if u provide output also its better
    thank you

  10. Bromo says:

    Hi, I wanna set authentication-provider to jdbc-user-service but I wanna it to be set against Google App Engine DataStore. How to do it? any clue sir?

  11. 2Ch says:


    I used your guide to build my S. Security configuration, and it works very well, thank you! :)

    However, I am experiencing a problem when I log out user1 and try to log in as user2: I get a viewExpired error after sucessful authentication. I am using JSF 1.2, Richfaces, Spring 2.5.4 and S. Security 2.0.4, all running in a JBOSS AS 4.2.3.

    Would you have a clue for me? I believe I am having problem with session management, but I was unable to figure exactly what I have to do. I believe I will have to make a logout filter, but I still do not know what to put inside it.

    Thank you!


  12. Biren says:

    Now i am able to authenticate user using database. Now I have few links which is to be restricted to other user except ROLE_ADMIN in jsp, How can i do this Can any one please answer this?

  13. HKS says:


    i wonder in your books is there any explanation if we want to you or over write UserDetailService ??? the above example use jdbcdaoimpl

  14. Exploring Google and OpenID login with Spring Security and Spring Roo « BSG Dev says:
  15. Joset Zamora says:

    I wish I have read this before when I was still learning Spring Security. I should have been able to save a lot of time. :) Thanks Peter!

  16. rame2uk says:

    great work keep on update

  17. shankha says:

    Great Tutorial…
    Where can i find the source code for this?

  18. MR newlearner says:

    Hi, I am having issues creating custom login jsp page. I have jsp page posting to Spring controller method. How can I make a login jsp page which will post to spring controller rather than j_spring_security_check as the action j_spring_security_check is needed for spring security?

  19. MR newlearner says:

    can someone please help. i am really struggling with this :(
    I am trying to create custom login page using spring security. But its not authenticating the user and i want it to post to my login controller method. How can I make it authenticate?

    Please help thanks.

  20. MR newlearner says:

    anyways i figured out myself. j_spring_security can be filtered by AuthenticationProcessingFilter. Extend this filter class and in there you can do what you want.

  21. dew says:

    Thanks a lot. I got great help in this article.
    I have another issue, could you show me your comments?

    I add a own login page named ‘login.jsp’. It works.
    But when i want to use tag ‘ spring:message ‘ for i18n ,i found it doesn’t work, in same time, other pages works well.
    So how can I resolve it?

  22. dew says:

    Thanks a lot. I got great help in this article.
    I have another issue, could you show me your comments?

    I add a own login page named ‘login.jsp’. It works.
    But when i want to use tag ‘spring:message’ for i18n in ‘login.jsp’ ,i found it doesn’t work, in same time, other pages works well.
    So how can I resolve it?

  23. pmularien says:

    @dew, are you sure you have declared the spring taglib at the top of your page? e.g.
    <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

  24. dew says:

    @pmularien, thanks for your quickly reply :)
    yes, i’m sure. I also declared spring tag lib

    following is the exception error msg when I use tag ” in ‘login.jsp’
    javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code ‘betHomeTitle’ for locale ‘zh_CN’.

    ps: other jsp pages with tag work well.

  25. dew says:

    @pmularien, thanks for your quickly reply :)
    yes, i’m sure. I also declared spring tag lib
    ‘%@ taglib uri=”http://www.springframework.org/tags” prefix=”spring”%’

    following is the exception error msg when I use tag ‘spring:message code=”betHomeTitle”‘ in ‘login.jsp’
    javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code ‘betHomeTitle’ for locale ‘zh_CN’.

    ps: other jsp pages with spring:message tag work well.

  26. A Quick Spring Security Lock-Down | The Coding Bone says:

    […] Peter Mularien, 5 Minute Guide to Spring Security <http://www.mularien.com/blog/2008/07/07/5-minute-guide-to-spring-security/&gt; GA_googleAddAttr("AdOpt", "1"); GA_googleAddAttr("Origin", "other"); […]

  27. Technical Related Notes » Blog Archive » links for 2010-08-03 says:

    […] " 5 Minute Guide to Spring Security – It's Only Software (tags: spring java) […]

  28. txedo says:

    Hello, I am trying to integrate Sprint Security and Struts2. I followed this tutorial but I get the following error:
    2011-05-10 19:35:12.149::WARN: failed springSecurityFilterChain
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘springSecurityFilterChain’ is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:360)

    Does anyone know how to fix it? Thank you in advance.

  29. Jeeba says:

    Thanks, this way of doing tutorials is so great. One question though, what if I want to put a message that the password or user is empty? . I know, it sound crazy but believe me, people do that kind of stuff. I was thinking on using the authentication-failure-url and Javascript to see that if we had an error in the authentication, and a GET param is send (like ?error=1) , then look if the user leaved empty spaces in the login form, but maybe there is another way to send the real cause for the authentication to not be fullfiled. Like sending error=1 when the user leaves the user empty, 2 when the user leave the password empty, 3 when the password and/or user doesnt match, and so for. Is this possible?

  30. Mr. Bean says:

    Where is the tag “(security:remember-me user-service-ref=”userDetailsService” key=”some_key”/)”


  31. springbeginer says:

    please help me if there is 200 roles and role mapping are there is there any “too many connections” problem will race ,because we are using jdbctempalte datasource

    please help me

  32. tuna says:

    Thank you for this tutorial regarding how to configure Spring Security. I’ve found it beneficial while integrating Spring Security in one of my projects.

  33. pmularien says:

    Glad I could help!

  34. Using other authentication services | How to Design Java Web Applications with Spring, Hibernate, Maven, TDD, and more | by Althea Parker says:

    […] all the users in an xml file. So, no need for the database here! I found this code example here. Of course, the passwords are not a big secret when you know that the encryption algorithm is MD5. […]

  35. Alberto says:

    I’ve read a lot of tutorial during a few days and I just can tell you THANKS for this clear explanation

    Really useful!

  36. ramonypp says:

    Where can i download this example?

  37. Satishkumar.v says:

    I Did not get a thing. It would be much better if explained what tag does what..? And flow goes from where to where. pls Explain

  38. Arun says:

    i am new in spring.i try your example but everytime i redirect to authemtication failure-url.Here is my spring-security.xml



  39. JavaPins says:

    » 5 Minute Guide to Spring Security – It’s Only Software…

    Thank you for submitting this cool story – Trackback from JavaPins…

  40. How should I secure my webapp written using Wicket, Spring, and JPA? says:

    […] Security (guide) – looks complete, but every guide I find that combines it with Wicket still calls it Acegi […]

  41. Kamal Giri says:

    great tutorial towards spring security keep update.

  42. altmer88 says:

    Thanks for manual

  43. Julián says:

    Hello Peter, I am stucked with Spring Security and JPA. I don’t know how to reference dataSource because my database is described in persistence.xml.
    How can I reference my database? It is some mechanism in order to reference dataSource in element?

    Thanks and regards.

  44. Shiva says:

    Nice tutorial.
    Where i an find th code?

  45. feodosij says:

    Thanks for the tutorial! Here’s an update. With Spring 3.0, some of the Spring classes were deprecated. The classes imported into the JSP should change as follows:

    <%@ page import="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter" %>
    <%@ page import="org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter" %>
    <%@ page import="org.springframework.security.core.AuthenticationException" %>

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>