Spring Security form login example
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.
In this example, last Spring Security hello world example will be reused, enhance it to support custom login form.
Technologies used :
- Spring 3.0.5.RELEASE
- Spring Security 3.0.5.RELEASE
- JSTL 1.2
1. Directory Structure
Review final directory structure of this tutorial.

2. Spring Security
Defined your custom login form in Spring XML file. See explanation below :
- login-page=”/login” – The login form will be “/login”
- default-target-url=”/welcome” – If authentication success, forward to “/welcome”
- authentication-failure-url=”/loginfailed” – If authentication failed, forward to “/loginfailed”
- 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>
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.
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 :
- j_spring_security_check – Login service
- j_spring_security_logout – Logout service
- j_username – Username
- 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
[/caption]2. If username/password is wrong, authentication failed, display custom error messages.
URL : http://localhost:8080/SpringMVC/loginfailed

3. If username/password is correct, authentication success, display requested page.
URL : http://localhost:8080/SpringMVC/welcome

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.





[...] Spring Security form login example. Tagged with: login • springSecurity If you enjoyed this article, please consider sharing it! [...]
I got error at j_spring_security_check..Can you give me explanation about that? and where I can configure that?
Hi,
I wanted to secure my REST Easy web service.Can i do it with this spring security example.
hi,
in a web application we insert password using md5 + some password encoding logic .
now the problem is for login in we are using spring authentication,
how to create the same encoding technique and pass the password to the same so that the authentication can be done with the encoded password
i gone through Adding a Password Encoder
but its through error when i create custom class
please help
In database you have to store only password hashes.
And you need two tables – users and authorities (follow this link
http://static.springsource.org/spring-security/site/docs/3.1.x/referencespringsecurity-single.html#appendix-schema )
Look here too:
http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-auth-providers
For instance, I just created two above mentioned tables (users and authorities), inserted data (including already encrypted passwords using org.springframework.security.crypto.password.StandardPasswordEncoder), configured data source bean, and in the security config file I have the following lines:
=====================================================================
====================================================================
where “adminDataSource” is a datasource bean defined in another config file.
And all works fine.
Sorry, used tag, so peace of my xml code is missing. Here it is:
I got thsi working, but my question is, I am using RichFaces. So say after login, teh user is clicking on a link, how do i force it to check for the authentication? The ‘/welcome’is only for spring right? If they click on a link later and the Faces-Config.xml has the file mapped somwehre else /pages/user/homepage.xhtml, how does that get authenticated? If the user doesn’t have access, it should go back to teh login page.
Thanks for this helpful tutorial.
Solved my problem !!
Nice article. I have it running OK.
I’m trying to modify it to use spring validation annotations, BeanPropertyBindingResult and form:errors in place of the ‘error’ attribute and ‘SPRING_SECURITY_LAST_EXCEPTION’.
This almost seems to work, but if I submit say an invalid password (not an empty one), the BindingResult comes back with null username and password, so form:errors displays: ‘default message [may not be empty]‘.
My error just just be about the password being invalid, not that both values ‘may not be empty’.
How can I get the correct ‘login’ object and ‘result’ errors into the View?
Hi, I’ve tried and it works…It’s a fantastic tutorial!!!!
Now, I would like to do an upgrade, adding a postgres database (with or without hibernate), where I would store all the authentication credential and first and last name…so, when the login is gonna success, I could see the page “Welcome mr….”
Thanks
HI I am trying to use your example my app contains spring 2.5 spring security 2.0.7
But every time i click on login i got this error The requested resource (/springhibernate/user/j_spring_security_check) is not available.
App configuration is like this
login.jsp
Login controller
spring secuirty xml
spring xml
web.xml
Can you check what is i am missing in this configuration
Too long, sorry, i have no time to check it line by line.
Solution :
Download the attached example, compare with yours and spot the different :)
Friend Virendra,
Me too faced the same problem. And solved by this code.
Just add this in spring-security.xml.
This code worked for me. I use Spring 3.1.1, tomcat 7.0.22.
I found
java.lang.NullPointerException
at java.util.Hashtable.get(Hashtable.java:334)
at org.apache.tomcat.util.http.Parameters.getParameterValues(Parameters.java:195)
at org.apache.tomcat.util.http.Parameters.getParameter(Parameters.java:240)
at org.apache.catalina.connector.Request.getParameter(Request.java:1088)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:355)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
at org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler.determineTargetUrl(AbstractAuthenticationTargetUrlRequestHandler.java:86)
at org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler.handle(AbstractAuthenticationTargetUrlRequestHandler.java:67)
at org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler.onLogoutSuccess(SimpleUrlLogoutSuccessHandler.java:28)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:381)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:168)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
when I click logout link
I got the same. Did you find out the cause ?
Regards
V
[...] 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 [...]
[...] to use database to perform the form-based login authentication in Spring Security. Note The last form-based login example will be reused, but the user details are move from XML file to database.Technologies used :Spring [...]
[...] hashing example Published: August 18, 2011 , Updated: August 18, 2011 , Author: mkyongprintIn last Spring Security form login example, the password is stored in clear-text, it is vulnerable to attack. In practice, it is always [...]
[...] Last Spring Security form-based login example will be reused, but switch authentication to support HTTP basic.1. Spring SecurityTo enable HTTP [...]
[...] 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 [...]