Saturday 19 October 2013

Spring Security Form Login Example

Posted by Kanhaiya
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 and how to create a custom login form and ask Spring Security to use it for login authentication. After implemented Spring security, to view the content of the page, users need to key in correct “username” and “password”.

Required Tools used:
  • Spring 3.0.5.RELEASE
  • Spring Security 3.0.5.RELEASE
  • JSTL 1.2
  • Tomcat 7
  • Jdk 1.7
  • Maven 3

1. Directory Structure
Review final directory structure of this tutorial


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

	4.0.0
	Spring-Security-Form-Login-Example
	Spring-Security-Form-Login-Example
	0.0.1-SNAPSHOT
	war
	Spring-Security-Form-Login-Example
	Spring Security Form Login Example
	http://maven.apache.org

	
		3.0.5.RELEASE
	

	

		
		
			org.springframework
			spring-core
			${spring.version}
		

		
			org.springframework
			spring-web
			${spring.version}
		

		
			org.springframework
			spring-webmvc
			${spring.version}
		

		
		
			org.springframework.security
			spring-security-core
			${spring.version}
		

		
			org.springframework.security
			spring-security-web
			${spring.version}
		

		
			org.springframework.security
			spring-security-config
			${spring.version}
		

		
		
			javax.servlet
			jstl
			1.2
		

	
	
		SpringSecurityFormLoginExample
		
			
				maven-compiler-plugin
				3.1
				
					1.7
					1.7
				
			
			
				maven-war-plugin
				2.3
				
					webapp
					false
				
			
		
	

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

File : web.xml

	Spring-Security-Form-Login-Example

	
	
		mvc-dispatcher
		org.springframework.web.servlet.DispatcherServlet
		1
	
	
		mvc-dispatcher
		/
	

	
		org.springframework.web.context.ContextLoaderListener
	

	
		contextConfigLocation					/WEB-INF/mvc-dispatcher-servlet.xml, 			/WEB-INF/spring-security.xml 			

	
	
		springSecurityFilterChain
		org.springframework.web.filter.DelegatingFilterProxy
	

	
		springSecurityFilterChain
		/*
	


4. Spring Configuration
File : mvc-dispatcher-servlet.xml


	

	
		
			/WEB-INF/pages/
		
		
			.jsp
		
	

	
		
			
				mymessages
			
		
	


5. Spring Security : User Authentication
Defined your custom login form in Spring XML file (spring-security.xml). See explanation below :
  1. login-page=”/login” – The login form will be “/login”
  2. default-target-url=”/welcome” – If authentication success, forward to “/welcome”
  3. authentication-failure-url=”/loginfailed” – If authentication failed, forward to “/loginfailed”
  4. logout-success-url=”/logout” – If logout , forward to “/logout
File : spring-security.xml


	
		
				
	

	
		
			
				
			
		
	


6. Spring MVC Controller
Spring controller to handle what URL should go where.
/**
 * 
 */
package com.kanha.controller;

import java.security.Principal;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author kanhaiya.sahu
 *
 */
@Controller
public class LoginController {

	@RequestMapping(value="/welcome", method = RequestMethod.GET)
	public String printWelcome(ModelMap model, Principal principal ) {
 
		String name = principal.getName();
		model.addAttribute("username", name);
		model.addAttribute("message", "Spring Security Custom Form example");
		return "hello";
 
	}
 
	@RequestMapping(value="/login", method = RequestMethod.GET)
	public String login(ModelMap model) {
 
		return "login";
 
	}
	
	@RequestMapping(value="/loginfailed", method = RequestMethod.GET)
	public String loginerror(ModelMap model) {
 
		model.addAttribute("error", "true");
		return "login";
 
	}
	
	@RequestMapping(value="/logout", method = RequestMethod.GET)
	public String logout(ModelMap model) {
 
		return "login";
 
	}
}

7. Error Messages
Default Spring’s error message is not user friendly enough. So define a custom error message with override the Spring’s “key” with your custom error message. In this case, just override “AbstractUserDetailsAuthenticationProvider.badCredentials“.

File : mymessages.properties
AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid username or password
8. JSP Views
In custom login form, you have to follow Spring Security standard name :
  1. j_spring_security_check – Login service
  2. j_spring_security_logout – Logout service
  3. j_username – Username
  4. j_password – Password
To display authentication error messages, use this :
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
File : login.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


Login Page



	

Login with Username and Password (Custom Page)

Your login attempt was not successful, try again. Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
User:
Password:


File: hello.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


	

Message : ${message}

Username : ${username}

" > Logout
Step 9: Run this Application
Run as a server and deploy in Tomcat 7. While browsing the project you will get the following screen for loging:

1. Access URL “http://localhost:8080/Spring-Security-Form-Login-Example/welcome“, Spring will redirect to your custom login form.
URL : http://localhost:8080/Spring-Security-Form-Login-Example/login


2. If username/password is wrong, authentication failed, display custom error messages.
URL : http://localhost:8080/Spring-Security-Form-Login-Example/loginfailed


3. If username/password is correct, authentication success, display requested page.
URL : http://localhost:8080/Spring-Security-Form-Login-Example/welcome



Download Source Code
SrcCodes: Spring-Security-Form-Login-Example.zip


1 comment: