Spring Security - Tutorial With Example

In this spring security tutorial and example, we will create a basic login authentication example that comes with spring security. This tutorial will focus on the security configuration using Spring Security 3.1. 

Required Libraries

Following libraries will be required to be in classpath in order to run this spring security login example.

Spring Security in the web.xml

The architecture is based entirely on servlet filters. Keeping this in mind, to begin with, a filter needs to be declared in the web.xml of the application. This links Spring Security's internal servlet filters into the servlet container's infrastructure

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

 <display-name>Spring Security Tutorial Application</display-name>

 <!-- - Location of the XML file that defines the root application context 
  - Applied by ContextLoaderListener. -->


 <!-- - Provides core MVC application controller. See example-servlet.xml. -->



Please note that the filter name should be named as 'springSecurityFilterChain' because spring security container creates the default bean with this name.

Spring Security configuration For User Authentication

Let's create spring-security.xml under WEB-INF folder to add spring security configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"

 <http use-expressions="true" entry-point-ref="loginUrlAuthenticationEntryPoint">
  <intercept-url pattern="/login.do" access="permitAll" />
  <intercept-url pattern="/jsp/*" access="isAuthenticated()"/>
 <beans:bean id="loginUrlAuthenticationEntryPoint"
  <beans:property name="loginFormUrl" value="/login.do" />
 <beans:bean id="securityFilter"
  <beans:property name="authenticationManager" ref="authenticationManager" />
  <!--  When user provides correct username/password and authentication is successful -->
  <beans:property name="authenticationSuccessHandler"
   ref="authenticationSuccessHandler" />
 <authentication-manager alias="authenticationManager">
    <user name="chuck.norris" password="cnorris" authorities="ROLE_ADMIN" />
    <user name="user" password="user" authorities="ROLE_USER" />

 <beans:bean id="authenticationSuccessHandler"
  <beans:property name="defaultTargetUrl" value="/home.do" />

Basics of Spring Security Configuration
  • The <http> block states that we want to use web security (which is applied by Spring Security's filters), with form-based login and access control expressions enabled. 
  • entry-point-ref attribute defines a customized AuthenticationEntryPoint to be set. Here default entry point refers login.do which directs the user to login.jsp
  • The first <intercept-url> element says that the login url ("/login.do") is accessible to anyone (the "permitAll" expression).
  • The second <intercept-url> elements says that in order to access any url starting with '/jsp', user needs to be authenticated. If user is not authenticated and it tries to open such url directly, he/she will be redirected to entry point i.e. login page. You can define all such url patterns (one per <intercept-url> element) for which authentication is required.
  • The <authentication-manager> element is being used here to define a list of in-memory users and their passwords and role information, which is convenient for samples and demos. A real world application would more likely use a database, LDAP server or some single sign-on integration.
  • authenticationSuccessHandler property declares a url which user is directed to upon successful authentication.

Sample Login Form

 Let's create a form based login jsp page

<%@ taglib prefix="c" 
           uri="http://java.sun.com/jsp/jstl/core" %>
<body onload='document.f.j_username.focus();'>
 <h3>Spring Security Login Example</h3>
 <c:if test="${not empty error}">
   Your login attempt was not successful, try again.<br /> Caused :
 <form name='loginForm' action="j_spring_security_check"
    <td><input type='text' name='j_username' value=''>
    <td><input type='password' name='j_password' />
    <td colspan='2'><input name="submit" type="submit"
     value="submit" />

Please note that the name of form, name of input for username and password have to be matched as given. The reason is spring uses these default names in its spring security container.

Sample home.jsp

Let's create a sample home page to which user will be redirected upon successful user authentication.

 <h3>Spring Security Welcome Page</h3>

   <td>Welcome To Home Page Of Spring Security</td>

Dispatcher Servlet Configuration & Controllers

Let's create a dispatcher configuration and LoginController which will map login.do and home.do urls to their respective jsps.
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
 <context:annotation-config />
 <context:component-scan base-package="com.javakart.springsecurity.controller" />
 <bean id="viewResolver"
  <property name="prefix">
  <property name="suffix">

package com.javakart.springsecurity.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

public class LoginController {

 @RequestMapping(value="login.do", method = RequestMethod.GET)
 public ModelAndView showLoginPage(){
  ModelAndView modelAndView = new ModelAndView("login");
  return modelAndView;
 @RequestMapping(value="home.do", method = RequestMethod.GET)
 public ModelAndView showHomePage(){
  ModelAndView modelAndView = new ModelAndView("home");
  return modelAndView;

Showing a Demo

1. Open “http://localhost:8080/SpringSecurity/jsp/home.jsp“, Spring Security will intercept the request and redirect to “http://localhost:8080/SpringMVC/login.do” and display the login page as below.

2. Try to enter wrong credentials (javakart/javakart), spring security filter will fail this authentication and will show the login page with error as follow.

3. Try to enter right credentials (user/user) and it will redirect the user to home page as follow.


  1. You explain it in very easy way.... Thank you very much, but I have one concern, in spring-security.xml when user successfully logged in it would be redirected to home.do.

    But I code in the same manner but it woudn't get redirected to home.do

    Please explain..

  2. thank you very much, but i don't find any path between LoginController.java file with any other else, how does it work?

  3. thank you ....

    My application doesnot find the intercept url

  4. Here, we are using annotations, In LoginController ModelAndView returns login or home . So, spring find the corresponding page in jsp folder with the help of InternalResourceViewResolver which helps to locate result pages using View name, which is returned by Controller

  5. If you share your source code,then it will best for us.. thanks

  6. thanks for good content.

    one quick query:

    Dispatcher Servlet Configuration & Controllers = what is the file name of this conf bean file?

  7. Thank you so much to give the basic idea abut spring security

  8. Hi,
    Please excuse me that i m not finding ur source code to download. cam u plz helkp me to find this.

    Thanx in advance