Secure your web application with Spring Security

Spring Security is great framework to secure web application. It’s easy to configure and it doesn’t need to make special changes or deploy libraries to your Servlet or EJB container.

Spring security keeps your application objects free of security code, unless you specifically choose to interact with the security context.


Photo credit: V.Áron

This article explains how to secure a JEE application with Spring Security by a sample project. This project is implemented with JSF, Spring (version 3.0) and Hibernate.

The source code of the project is available on github here.

Basic configuration

In this part we will add dependencies and basic configuration to integrate Spring security to the web application.

  • Add Spring Security dependencies to the maven pom.xml file.

– Update web.xml file.
Inside web.xml, insert the following block of code. It should be inserted right after the /context-param end-tag.


– Add applicationContext-security.xml file
This file contains the basic Spring Security config. There is no user access control for any path. Users are defined in the Spring application context file.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=""
 <http use-expressions="true">
        <intercept-url pattern="/**" filters="none" />
        <form-login />
        <logout />

	        <user name="user1" password="password1" authorities="ROLE_USER, ROLE_ADMIN" />
	        <user name="user2" password="password2" authorities="ROLE_USER" />

After the basic configuration is done, you should have your web application running and you should access all pages.

Security Configuration

1 – Authentication

Authentication is the process of determining whether someone or something is, in fact, who or what it is declared to be. [2]

Spring security supports LDAP, database, XML and Properties file to authenticate users. In this article, we use database authentication. The database schema is created by hibernate and it is populated by DbUnit framework.

We create two persistent classes to save users and their authorities.

– Create a login.xhtml page as shown in the code bellow

<html xmlns:jsp=""

<c:if test="${param.state=='failure'}">
		<c:set var="username" value="#{sessionScope.SPRING_SECURITY_LAST_USERNAME}"/>
		<div class="ERROR">
			Your login attempt was not successful, try again.<br />
			Reason: #{sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}
	<form  action="#{request.contextPath}/j_spring_security_check" method="post">
		<h:panelGrid columns="2" title="Customer">
			<f:facet name="header"> 
				<h:outputText value="Login form" />
			<h:outputText value="User:" />
			<h:inputText id="j_username" value="#{username}"  />
			<h:outputText value="Password:" />
			<h:inputSecret id="j_password" />
			<f:facet name="footer"> 
				<h:commandButton  value="Login" type="submit"  />

To add JDBC Spring security some changes nead to be done to the applicationContext-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns=""
	xmlns:beans="" xmlns:xsi=""

	<http use-expressions="true" access-denied-page="/pages/static/accessDenied.jsf">
		<intercept-url pattern="/login.jsf" filters="none"/>
		<intercept-url pattern="/pages/**" access="isAuthenticated()" />
		<form-login login-page="/login.jsf" default-target-url="/pages/static/welcome.jsf" authentication-failure-url="/login.jsf?state=failure"/>
		<logout logout-success-url="/login.jsf?state=logout"  />

	<authentication-manager alias="authenticationManager">
			<password-encoder hash="md5" />
			<jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="SELECT U.login AS username, U.password as password, U.enabled as enabled FROM user U where U.login=?"
				authorities-by-username-query="SELECT U.login as username, A.authority_name as authority FROM user U, authority A WHERE U.user_id=A.user_id and U.login=?"
				role-prefix="ROLE_" />


To maximize password security we made a choice to use md5 password encoding.

2 – Authorization

Authorization is the function of specifying access rights to resources, which is related to information security and computer security in general and to access control in particular. More formally, “to authorize” is to define access policy. [1]

With spring security we can manage pages, screen components and methods execution rights policies.

– Path access control

Then implement access rules for URLs by adding <intercept-url> children directly under the <http> element.

	<http use-expressions="true" access-denied-page="/pages/static/accessDenied.jsf">
		<intercept-url pattern="/login.jsf" filters="none" />
		<intercept-url pattern="/pages/static/**" access="isAuthenticated()" />
		<intercept-url pattern="/pages/customer/**" access="hasAnyRole('ROLE_ADMIN','ROLE_CUSTOMER')" />
		<intercept-url pattern="/pages/order/**" access="hasAnyRole('ROLE_ADMIN','ROLE_ORDER')" />
		<intercept-url pattern="/pages/admin/**" access="hasRole('ROLE_ADMIN')" />
		<form-login login-page="/login.jsf" default-target-url="/pages/static/welcome.jsf"
			authentication-failure-url="/login.jsf?state=failure" />
		<logout logout-success-url="/login.jsf?state=logout" />

-Taglib Spring Security

Sometimes, it is better to hide some unauthorized links rather than letting them available and showing the access denied page when they are requested.

Spring Security has its own taglib which provides basic support for accessing security information and applying security constraints in JSPs. [3]

To use Spring security taglib in JSP pages, you need to add the taglib declaration to your project as shown in the source code bellow:

<%@ taglib prefix="sec" uri="" %>
<sec:authorize ifAllGranted="ROLE_USER">
  Utilisateur : <sec:authentication property="principal.username"/>

To use Spring security Taglib in a facelets pages is a little bit more complicated.

  • We need to add XML namespaces declaration for Spring security taglib into facelet page as highlighted in this source code.
<html xmlns=""
  • Create springsecurity.taglib.xml file into the WEB-INF file and a param declaration to reference this file in the web.xml file.

This is the source code of springsecurity.taglib.xml I used in this prototype project. But this file has to be changed if you are using JSF 2.0. For more detail, read the spring documentation in this link.

<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC
  "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
		<function-signature>boolean areAllGranted(java.lang.String)</function-signature>
		<function-signature>boolean areAnyGranted(java.lang.String)</function-signature>
		<function-signature>boolean areNotGranted(java.lang.String)</function-signature>
		<function-signature>boolean isAllowed(java.lang.String, java.lang.String)</function-signature>

  • Add this dependency to the pom.xml file

Usually, the admin menu panel is visible only for users having the admin role. To implement this behavior, the panel source code is nested into the spring security authorize tag.

<sec:authorize access="hasAnyRole('ROLE_ADMIN')" >
	<rich:panelMenuGroup label="Admin">
		<rich:panelMenuItem >
				 <h:outputLink value="../admin/admin.jsf" >Users</h:outputLink>

-Method authorization

Spring security allows method execution authorization management. It provides annotations which can contain expression attributes which are applied before and after the method invocation. To enable support for them, the attribute global-method-security has to be assigned the value enabled:

<global-method-security pre-post-annotations="enabled"/>

The source code above is added to application-context-security.xml file.

In this example we made a choice to allow only users having ROLE_CUSTOMER role to add customers.

import com.mycompany.dao.ICustomerDao;
import com.mycompany.entity.Customer;

public class CustomerDao extends HibernateDaoSupport implements ICustomerDao{

    public void save(Customer customer) {

// Other methods ....


To test Spring method execution authorization, we created a user “orderManager” which doesn’t have the role ROLE_CUSTOMER. When this user tries to save a customer, the application display the caught error message “Access is denied”.

Application example (Access is denied message)

Spring Security is a powerful framework to secure JEE applications. It has many other features to manage authentication and access-control services for java/JEE applications. I had used Spring Security since the project had a name Acegi. I think that the framewok has made a lot of progress and I recommend it for Securing web applications.


13 thoughts on “Secure your web application with Spring Security

  1. Very good article. But when I built and deployed this war to the tomcat 6.0.20 (JDK 1.6.0_17) the console shows the below error

    2011-01-21 11:19:27 DefaultListableBeanFactory [DEBUG] Retrieved dependent beans for bean ‘(inner bean)#7’: []
    2011-01-21 11:19:27 DisposableBeanAdapter [DEBUG] Invoking destroy method ‘close’ on bean with name ‘dataSource’
    Jan 21, 2011 11:19:27 AM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
    SEVERE: The web application [/myApp_Security] registered the JBDC driver [org.hsqldb.jdbcDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.

    1. Thank you for your comment, It helps me improve my blog content.
      You can checkout the code source of the application from google code SVN in this link :
      You can olso browse the code in this link

      This project uses maven2 as project management tool. You need to install maven and to add JBoss repository to the setting.xml file in maven conf directory. For more detail you can read the RichFaces documentation in this link :

      I hope these details will help you.

  2. Hello, This is a great example. I was following your example except for pages/static/accessDenied.jsf. When you log on as someone with ROLE_CUSTOMER and access a page with ROLE_ADMIN, I expect to get routed to static/accessDenied.jsf, Instead I get a 403 sent back to the screen.

    1. Hi,
      I hope this example helped you.

      I tried a test. I gave to all users the access to admin menu links without changing the spring URL interceptors configuration.
      When I try access admin links, I get access denied page.

      I would like to know if you have this problem where you are testing this article project example or in your own project.

      If you are using this example can you give me step by step the use case?

      If you have problem in your project I need some extra information Tomcat log or some parts of XML configuration?

  3. I found the problem. It was with IE8 displaying friendly messages for http return codes 🙂
    Thank you very much for your example.

  4. Great Job, it’s almost working but I have a problem. Whe you use it seems that the value characters are escaped so the value is not showing fine in the form. Do you know anyway of unescape the last user name?, something similar to but applied to your code?.
    Many thanks

  5. Est ce que vous pouvez m’indiquer comment tester le projet,
    je l’ai télécharger via svn check out mais je peux pas faire run as server application


  6. You nead to install maven or to use the maven plugin of your IDE.
    *Case 1: Maven
    Create the war run : mvn war:war
    Deploy the war run after updation pom file: mvn tomcat:deploy
    update plugin part change tomcat url, user and password

    *Case2: Eclipse
    Istall maven plugin
    Right click in your project -> Maven -> enable dependency management.
    Run as a web project

  7. Simply want to say your article is as astonishing.
    The clearness in your put up is just nice and that i could assume you’re an expert in this subject. Well with your permission allow me to grasp your feed to stay up to date with drawing close post. Thank you a million and please carry on the gratifying work.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s