Spring Security allows developer to integrate security features with J2EE web application easily, it highjacks incoming HTTP request via servlet filters, and implements “user defined” security checking.

In this tutorial, we show you how to integrate Spring Security 3.0 with Spring MVC web application to secure URL access. After implemented Spring security, to view the content of the page, users need to key in correct “username” and “password”.

Technologies used :

  1. Spring 3.0.5.RELEASE
  2. Spring Security 3.0.5.RELEASE
  3. Eclipse 3.6
  4. JDK 1.6
  5. Maven 3
Note
Spring Security 3.0 requires Java 5.0 Runtime Environment or higher

1. Directory Structure

Review the final directory structure of this tutorial.

directory structure

2. Spring Security Dependencies

To use Spring security 3.0, you need “spring-security-core.jar“, “spring-security-web.jar” and “spring-security-config.jar“. Spring libraries are available in Maven central repository.

File : pom.xml

	<properties>
		<spring.version>3.0.5.RELEASE</spring.version>
	</properties>
 
	<dependencies>
 
		<!-- Spring 3 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
	</dependencies>
 
</project>

3. Spring MVC Web Application

A simple Spring MVC to return a “hello.jsp” page, via URI “/welcome“. Later use Spring security to secure this URL access.

File : HelloController.java

package com.mkyong.common.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
@RequestMapping("/welcome")
public class HelloController {
 
	@RequestMapping(method = RequestMethod.GET)
	public String printWelcome(ModelMap model) {
 
		model.addAttribute("message", "Spring Security Hello World");
		return "hello";
 
	}
 
}

File : hello.jsp

<html>
<body>
	<h1>Message : ${message}</h1>	
</body>
</html>

File : mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	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/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
	<context:component-scan base-package="com.mkyong.common.controller" />
 
	<bean
	  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	  <property name="prefix">
		<value>/WEB-INF/pages/</value>
	  </property>
	  <property name="suffix">
		<value>.jsp</value>
	  </property>
	</bean>
 
</beans>

4. Spring Security : User Authentication

Create a separate Spring configuration file to define Spring security related stuffs. It tells, only user with correct username “mkyong” and password “123456″ is allow to access URI “/welcome“.

Below Spring configuration should be self-explanatory.

File : spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="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.3.xsd">
 
	<http auto-config="true">
		<intercept-url pattern="/welcome*" access="ROLE_USER" />
	</http>
 
	<authentication-manager>
	  <authentication-provider>
	    <user-service>
		<user name="mkyong" password="123456" authorities="ROLE_USER" />
	    </user-service>
	  </authentication-provider>
	</authentication-manager>
 
</beans:beans>

5. Integrate Spring Security

To integrate Spring security with web application, just declare “DelegatingFilterProxy” as servlet filter to intercept incoming request.

File : web.xml

<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
	<display-name>Spring MVC Application</display-name>
 
	<!-- Spring MVC -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>
                    org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
 
	<listener>
		<listener-class>
                  org.springframework.web.context.ContextLoaderListener
                </listener-class>
	</listener>
 
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/mvc-dispatcher-servlet.xml,
			/WEB-INF/spring-security.xml
		</param-value>
	</context-param>
 
	<!-- Spring Security -->
	<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>
 
</web-app>

6. Demo

That’s all. But wait, where’s the login form? No worry, if you do not define login form, Spring will create a simple login form automatically.

Custom Login Form
Read this “Spring Security form login example” to understand how to create a custom login form in Spring Security.

1. Access “http://localhost:8080/SpringMVC/welcome“, Spring Security will intercept the request and redirect to “http://localhost:8080/SpringMVC/spring_security_login” automatically. And display the Spring predefined authentication form.

URL : http://localhost:8080/SpringMVC/spring_security_login

spring security demo

2. Error messages will be displayed if wrong username and password are provided.

URL : http://localhost:8080/SpringMVC/spring_security_login?login_error

spring security error forms

3. If correct username and password are provided, Spring security will redirect to the original requested URL and display the content of the page.

URL : http://localhost:8080/SpringMVC/welcome

spring security demo

Download Source Code

References

  1. Spring Security Features
  2. Spring 3 MVC hello world example
  3. Spring Security form login example (authentication)
Tags :
Founder of Mkyong.com, love Java and open source stuffs. Follow him on Twitter, or befriend him on Facebook or Google Plus.
Here are some of my recommended Books

Related Posts

Popular Posts