Spring security using custom login form

Spring by default provides auto login form, Most of the real time projects use their own custom login form instead of spring provided form.

Let’s see how such custom login form can be created and used in the spring security login flow.

Project structure

Follow steps from the Spring MVC project link to setup a spring maven hello world project.

Modify a web.xml file to have spring security filter as below

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.   <display-name>Archetype Created Web Application</display-name>
  6.  
  7.   <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <load-on-startup>1</load-on-startup>
  12.     </servlet>
  13.     <servlet-mapping>
  14.         <servlet-name>mvc-dispatcher</servlet-name>
  15.         <url-pattern>/</url-pattern>
  16.     </servlet-mapping>
  17.  
  18.     <listener>
  19.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  20.     </listener>
  21.     <!-- Loads Spring Security configuration file -->
  22.     <context-param>
  23.         <param-name>contextConfigLocation</param-name>
  24.         <param-value>
  25.             /WEB-INF/spring-mvc.xml,
  26.             /WEB-INF/spring-security.xml
  27.         </param-value>
  28.     </context-param>
  29.    
  30.         <!-- Spring Security filter -->
  31.     <filter>
  32.         <filter-name>springSecurityFilterChain</filter-name>
  33.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  34.     </filter>
  35.  
  36.     <filter-mapping>
  37.         <filter-name>springSecurityFilterChain</filter-name>
  38.         <url-pattern>/*</url-pattern>
  39.     </filter-mapping>
  40.    
  41. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

  <display-name>Archetype Created Web Application</display-name>
  
  <!-- Spring MVC dispatcher servlet -->
	<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>
	<!-- Loads Spring Security configuration file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-mvc.xml,
			/WEB-INF/spring-security.xml
		</param-value>
	</context-param>
	
		<!-- Spring Security filter -->
	<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>

Include spring security dependency in the pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>SpringProject</groupId>
  5.   <artifactId>SpringSecurityCustomLoginForm</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringSecurityCustomLoginForm Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.   <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.         <spring-security.version>3.2.7.RELEASE</spring-security.version>
  13.     </properties>
  14.   <dependencies>
  15.     <dependency>
  16.       <groupId>junit</groupId>
  17.       <artifactId>junit</artifactId>
  18.       <version>3.8.1</version>
  19.       <scope>test</scope>
  20.     </dependency>
  21.      <!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context, spring-web -->
  22.     <dependency>
  23.         <groupId>org.springframework</groupId>
  24.         <artifactId>spring-web</artifactId>
  25.         <version>${org.springframework.version}</version>
  26.     </dependency>
  27.      
  28.         <dependency>
  29.             <groupId>org.springframework</groupId>
  30.             <artifactId>spring-webmvc</artifactId>
  31.             <version>${org.springframework.version}</version>
  32.         </dependency>
  33.          
  34.         <!-- Spring Security Dependencies -->
  35.         <dependency>
  36.             <groupId>org.springframework.security</groupId>
  37.             <artifactId>spring-security-core</artifactId>
  38.             <version>${spring-security.version}</version>
  39.          </dependency>
  40.          <dependency>
  41.             <groupId>org.springframework.security</groupId>
  42.             <artifactId>spring-security-web</artifactId>
  43.             <version>${spring-security.version}</version>
  44.           </dependency>
  45.           <dependency>
  46.             <groupId>org.springframework.security</groupId>
  47.             <artifactId>spring-security-config</artifactId>
  48.             <version>${spring-security.version}</version>
  49.           </dependency>
  50.     <dependency>
  51.     <groupId>javax.servlet</groupId>
  52.     <artifactId>jstl</artifactId>
  53.     <version>1.2</version>
  54. </dependency>
  55. </dependencies>
  56.   <build>
  57.     <finalName>SpringSecurityHelloWorldCustomLogin</finalName>
  58.     <plugins>
  59.             <plugin>
  60.                 <groupId>org.apache.maven.plugins</groupId>
  61.                 <artifactId>maven-compiler-plugin</artifactId>
  62.                 <version>2.5.1</version>
  63.                 <configuration>
  64.                     <source>1.8</source>
  65.                     <target>1.8</target>
  66.                 </configuration>
  67.             </plugin>
  68.         </plugins>
  69.   </build>
  70. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringProject</groupId>
  <artifactId>SpringSecurityCustomLoginForm</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringSecurityCustomLoginForm Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
        <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
        <spring-security.version>3.2.7.RELEASE</spring-security.version>
    </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context, spring-web -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>${org.springframework.version}</version>
	</dependency>
     
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
         
        <!-- Spring Security Dependencies -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring-security.version}</version>
         </dependency> 
         <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring-security.version}</version>
          </dependency> 
          <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring-security.version}</version>
          </dependency>
	<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
	<version>1.2</version>
</dependency>
</dependencies>
  <build>
    <finalName>SpringSecurityHelloWorldCustomLogin</finalName>
    <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
  </build>
</project>

Create our custom login.jsp page

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8. <title>Insert title here</title>
  9. </head>
  10. <body>
  11. <c:if test="${error eq 'true'}">
  12. ${msg}
  13. </c:if>
  14. <form name='loginForm' action="<c:url value='j_spring_security_check' />"
  15. method='POST'>
  16.  
  17. <table>
  18. <tr>
  19. <td>User Name:</td>
  20. <td><input type='text' name='j_username' value=''>
  21. </td>
  22. </tr>
  23. <tr>
  24. <td>Password:</td>
  25. <td><input type='password' name='j_password' />
  26. </td>
  27. </tr>
  28. <tr>
  29. <td><input name="submit" type="submit"
  30. value="submit" />
  31. </td>
  32. <td><input name="reset" type="reset" />
  33. </td>
  34. </tr>
  35. </table>
  36.  
  37. </form>
  38. </body>
  39. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:if test="${error eq 'true'}">
${msg}
</c:if>
<form name='loginForm' action="<c:url value='j_spring_security_check' />"
method='POST'>
 
<table>
<tr>
<td>User Name:</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><input name="submit" type="submit"
value="submit" />
</td>
<td><input name="reset" type="reset" />
</td>
</tr>
</table>
 
</form>
</body>
</html>

Since we are creating our own jsp page for login, we need to maintain the spring security flow by using its own variables which are

User name should be stored in the parameter j_username

Password should be stored in the parameter j_password

Form submit should happen to the URL –> j_spring_security_check

Create home.jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>Hello World</title>
  8. </head>
  9. <body>
  10. <h4>Hi ${username} welcome !!</h4>
  11. </body>
  12. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<h4>Hi ${username} welcome !!</h4>
</body>
</html>

Create spring-security.xml

  1. <beans:beans xmlns="http://www.springframework.org/schema/security"
  2.     xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  4.          http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  5.          http://www.springframework.org/schema/security
  6.          http://www.springframework.org/schema/security/spring-security-3.2.xsd">
  7.  
  8.     <http auto-config='true'>
  9.         <intercept-url pattern="/secured/*" access="ROLE_USER" />
  10.         <form-login login-page="/login" default-target-url="/secured/home"
  11.             authentication-failure-url="/loginError" />
  12.     </http>
  13.  
  14.     <authentication-manager erase-credentials="true">
  15.         <authentication-provider>
  16.             <user-service>
  17.                 <user name="kb" password="kb1234" authorities="ROLE_USER" />
  18.             </user-service>
  19.         </authentication-provider>
  20.     </authentication-manager>
  21.  
  22. </beans:beans>
<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.2.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<http auto-config='true'>
		<intercept-url pattern="/secured/*" access="ROLE_USER" />
		<form-login login-page="/login" default-target-url="/secured/home"
			authentication-failure-url="/loginError" />
	</http>

	<authentication-manager erase-credentials="true">
		<authentication-provider>
			<user-service>
				<user name="kb" password="kb1234" authorities="ROLE_USER" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

</beans:beans>

In the login-page -> specify the path of controller which returns the custom login jsp, in our case it is /login , which is defined in the login controller below and highlighted

default-target-url specifies the path of a method in controller where it has to go after successful authentication, in our case it is /secured/home which is defined in the login controller below and highlighted

authentication-failure-url specifies the path of a method in controller where it has to go if authentication is failed.
In our case it is /loginError which is defined in the login controller below and highlighted.

Note : anything under /secured is intercepted by the spring security and is accessible by only the user who has the role called “ROLE_USER”

Create the LoginController class to map the requests

  1. package com.kb.controllers;
  2.  
  3. import java.security.Principal;
  4.  
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.ui.ModelMap;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RequestMethod;
  9.  
  10. @Controller
  11. public class LoginController {
  12.    
  13.     @RequestMapping(value="/login", method = RequestMethod.GET)
  14.     public String login(ModelMap model) {
  15.      
  16.     return "login";
  17.      
  18.     }
  19.    
  20.     @RequestMapping(value="/secured/home", method = RequestMethod.GET)
  21.     public String home(ModelMap model, Principal principal ) {
  22.      
  23.     String name = principal.getName();
  24.     model.addAttribute("username", name);
  25.     return "home";
  26.      
  27.     }
  28.      
  29.      
  30.     @RequestMapping(value="/loginError", method = RequestMethod.GET)
  31.     public String loginError(ModelMap model) {
  32.     model.addAttribute("error", "true");
  33.     model.addAttribute("msg", "invalid login credentials");
  34.     return "login";
  35.      
  36.     }
  37.  
  38. }
package com.kb.controllers;

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="/login", method = RequestMethod.GET)
	public String login(ModelMap model) {
	 
	return "login";
	 
	}
	
	@RequestMapping(value="/secured/home", method = RequestMethod.GET)
	public String home(ModelMap model, Principal principal ) {
	 
	String name = principal.getName();
	model.addAttribute("username", name);
	return "home";
	 
	}
	 
	 
	@RequestMapping(value="/loginError", method = RequestMethod.GET)
	public String loginError(ModelMap model) {
	model.addAttribute("error", "true");
	model.addAttribute("msg", "invalid login credentials");
	return "login";
	 
	}

}

Now Right click on the project and run as maven install
Copy the war file from project target folder to Tomcat’s /webapps folder.
Now start the server.

Access the below url
http://localhost:8080/SpringSecurityHelloWorldCustomLogin/login

you can see our custom login page instead of spring provided login form

Now provide wrong credentials and see the error

Now provide valid credentials
Username – kb
Password – kb1234

You can see, we entered into the secured page only after providing valid credentials.

Download this project SpringSecurityCustomLoginForm.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on