By default, if no login form is provided, Spring Security will create a simple login form automatically, see demonstration in this Spring Security hello world example.

In this tutorial, we show you how to create a custom login form and ask Spring Security to use it for login authentication.

Note
In this example, last Spring Security hello world example will be reused, enhance it to support custom login form.

Technologies used :

  1. Spring 3.0.5.RELEASE
  2. Spring Security 3.0.5.RELEASE
  3. JSTL 1.2

1. Directory Structure

Review final directory structure of this tutorial.

directory structure

2. Spring Security

Defined your custom login form in Spring XML file. 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

<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" />
		<form-login login-page="/login" default-target-url="/welcome"
			authentication-failure-url="/loginfailed" />
		<logout logout-success-url="/logout" />
	</http>
 
	<authentication-manager>
	  <authentication-provider>
		<user-service>
			<user name="mkyong" password="123456" authorities="ROLE_USER" />
		</user-service>
	  </authentication-provider>
	</authentication-manager>
 
</beans:beans>
Password in clear-text?
A pretty bad idea, you should always hash the password with SHA or MD5 algorithm, this tutorial show you how – Spring Security password hashing example.

3. Spring MVC Controller

Spring controller to handle what URL should go where.

Note
You may interest at this how to get the current logged user detail.

File : LoginController.java

package com.mkyong.common.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;
 
@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";
 
	}
 
}

4. Error Messages

Default Spring’s error message is not user friendly enough. Read this “how to display custom error message in Spring Security

File : mymessages.properties

AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid username or password

5. 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"%>
<html>
<head>
<title>Login Page</title>
<style>
.errorblock {
	color: #ff0000;
	background-color: #ffEEEE;
	border: 3px solid #ff0000;
	padding: 8px;
	margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>
	<h3>Login with Username and Password (Custom Page)</h3>
 
	<c:if test="${not empty error}">
		<div class="errorblock">
			Your login attempt was not successful, try again.<br /> Caused :
			${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
		</div>
	</c:if>
 
	<form name='f' action="<c:url value='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>
			<tr>
				<td colspan='2'><input name="reset" type="reset" />
				</td>
			</tr>
		</table>
 
	</form>
</body>
</html>

File : hello.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
	<h3>Message : ${message}</h3>	
	<h3>Username : ${username}</h3>	
 
	<a href="<c:url value="/j_spring_security_logout" />" > Logout</a>
 
</body>
</html>

6. Demo

1. Access URL “http://localhost:8080/SpringMVC/welcome“, Spring will redirect to your custom login form.

URL : http://localhost:8080/SpringMVC/login

custom login form[/caption]

2. If username/password is wrong, authentication failed, display custom error messages.

URL : http://localhost:8080/SpringMVC/loginfailed

login form error message

3. If username/password is correct, authentication success, display requested page.

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

login form success
Authentication using database
In practice, you should move the user details from XML file to database for authentication. This tutorial show you how – Spring Security form-based login using database.

Download Source Code

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