Spring Security Configuration with Spring MVC

This tutorial will show you the way to configure Spring Security with Spring MVC web application to secure mvc pages. We will take an spring mvc web application example in which, we will configure Spring Security to protect a page from outside access.

Tools used :

  • Spring MVC 3.0.3
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6

To understand the example you will need to have prior knowledge of Spring MVC. If you do not know the basics of Spring MVC the go to our Spring MVC Tutorial.

In our example, there is an example of welcome page that is managed by Spring MVC framework. We will configure Spring Security in this example and will make the welcome page secure. User have to authenticate herself to view welcome page.

Configuring web.xml for Spring Security

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id="WebApp_ID" version="2.5">
    <display-name>HelloWorldExampleWithSpring3MVCInEclipse</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-config.xml</param-value>
    </context-param>

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

    <servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/app-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

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

In web.xml, we have configured Spring MVC to manage the request came for the URL “*.htm”. For configuring Spring Security we do the following :

  1. First of all, we have to register org.springframework.web.filter.DelegatingFilterProxy filter in web.xml. This filter manages the securing of the web pages.
  2. The filter will manage the requested URL “/*”. That means all the requests will go through the filter so that it can authenticate the user of particulate web pages that we will configured as secured pages with Spring Security.
  3. Register org.springframework.web.context.ContextLoaderListener listener provided in Spring so that it can configure spring context on server startup.

Creating welcome page (welcome.jsp)


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page session="true" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Configuring Spring Security 3 - This is a secure page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
    </head>
    <body>
        <h1>Welcome!</h1><br />
        ${HelloMessage}<br />
    </body>
</html>

Our welcome page is very simple that only shows a message that is stored in model object. The message is  provided by the controller class.

Creating Welcome Controller class (WelcomeController.java)


package com.raistudies.actions;

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

@Controller
public class WelcomeController {

    @RequestMapping(value="/welcome",method=RequestMethod.GET)
    public ModelAndView sayHello(Model model){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("welcome");
        model.addAttribute("HelloMessage", "Hello World from Spring Security application.");
        return mv;
    }
}

As you can see annotation driven configuration has been used to make WelcomeController class as a controller and the sayHello method will manage the request for /welcome url.

Spring Securing Configuration file (securily.xml)

After that we will have to create a Spring Security Configuration file, in which have to define the security constrains that are to be applied to our application. You will see a lot of new things in this file. I will explain all the tags one by one make the things clear to you.


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

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/security


http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http realm="Project Realm" auto-config="true">
        <intercept-url pattern="/**" access="ROLE_ADMIN"/>
    </http>

    <authentication-manager>
        <authentication-provider>
            <password-encoder hash="md5"/>
            <user-service>
                <user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_ADMIN"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

</b:beans>
  1. <http/> tag is used to define security setting for web application for defining access constrains for pages, defining login pages, login process to use, activate remember me option, customizing session level setting etc. Here we have used only one option i.e.  <intercept-url pattern=“/**” access=“ROLE_ADMIN”/>. <intercept-url/> tag is used to define url patterns to be secure and the definition of the roles who can access them.  In our example all url patters are secured and only user will role ROLE_ADMIN can access the pages.
  2. <authentication-manager/> tag is used to define method of authentication of the user on the basis of that user will be able to access a page.
  3. <authentication-provider/> tag specifies the username and password provider. It can be also a database table. Here we have used hard coded username and password. Password is encrypted in md5 algorithm.

Spring Configuration File (app-config.xml)

This file is used to configure Spring MVC and import the security settings defined in security.xml.


<?xml version="1.0" encoding="UTF-8"?>
<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.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd


http://www.springframework.org/schema/mvc


http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.raistudies" />

    <!-- Importing Spring Security Settings  -->
    <import resource="security.xml"/>

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

<import/> tag is used to import the security settings defined in security.xml.

Running the example

Export the example as war and deploy it Tomcat 6 server. While browsing the project you will get the following screen for loging:

Spring Security Default Login Page

Spring Security Default Login Page

From where is this login page came? We have not created it. Actually, this is the default login page provided by Spring Security. We can also customize it to use our own login page. We will see an example also relate to this.

Put username and password as admin and click on Submit button. You will go to the welcome page.

Spring Security Secured Page

Spring Security Secured Page

If you type wrong password it will show you error on login page.

You can download source code of this example from bellow links. Deploy the war file to Tomcat 6 and see how to configure Spring Security.

Source: Download

War: Download

Related Posts:

Leave a comment ?

3 Comments.

  1. It is a matter shut to my heart cheers, in which are your speak to facts although?

  2. Your source code zip also contains the war file. Please post the source.

    Thanks!

  3. Thanks for good example, but why the password is “admin” when as I think it’s gonna be password=”21232f297a57a5a743894a0e4a801fc3″? And how to change it?

Leave a Comment Cancel reply


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>