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"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

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

 <!-- - Location of the XML file that defines the root application context 
  - Applied by ContextLoaderListener. -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>WEB-INF/spring-security.xml</param-value>
 </context-param>

 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <!-- - Provides core MVC application controller. See example-servlet.xml. -->
 <servlet>
  <servlet-name>dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
  <welcome-file>login.jsp</welcome-file>
 </welcome-file-list>
</web-app>

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"
 xmlns:sec="http://www.springframework.org/schema/security"
 xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

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

 <beans:bean id="authenticationSuccessHandler"
  class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
  <beans:property name="defaultTargetUrl" value="/home.do" />
 </beans:bean>
</beans:beans>




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" %>
<html>
<body onload='document.f.j_username.focus();'>
 <h3>Spring Security Login Example</h3>
 
 <c:if test="${not empty error}">
  <div>
   Your login attempt was not successful, try again.<br /> Caused :
   ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
  </div>
 </c:if>
 
 <form name='loginForm' action="j_spring_security_check"
  method='POST'>
 
  <table>
   <tr>
    <td>User:</td>
    <td><input type='text' name='j_username' value=''>
    </td>
   </tr>
   <tr>
    <td>Password:</td>
    <td><input type='password' name='j_password' />
    </td>
   </tr>
   <tr>
    <td colspan='2'><input name="submit" type="submit"
     value="submit" />
    </td>
   </tr>
  </table>
 
 </form>
</body>
</html>


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.


<html>
<body>
 <h3>Spring Security Welcome Page</h3>

 <table>
  <tr>
   <td>Welcome To Home Page Of Spring Security</td>
  </tr>
 </table>
</body>
</html>

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"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 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"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/jsp/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
</beans>



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;

@Controller
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.


9 comments:

  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..

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

    ReplyDelete
  3. thank you ....

    My application doesnot find the intercept url

    ReplyDelete
  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

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

    ReplyDelete
  6. thanks for good content.

    one quick query:

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

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

    ReplyDelete
  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
    Devesh

    ReplyDelete