HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Spring security login form example

By Lokesh Gupta | Filed Under: Spring Security

Learn to add Spring security login form to any spring web applications using detailed information discussed in spring security tutorial.

Table of Contents

1. Background information
2. Spring security maven dependencies
3. Configure DelegatingFilterProxy in web.xml
4. Add security configuration in application-security.xml
5. Update the controller
6. Add related JSP views
7. Test the application

Read More : Spring security 5 login form example [Updated for Spring 5]

1. Background information

We learned to integrate between Spring 3 and hibernate in linked post. That application was simple web application which presents a view where user can add/edit employees.

Lets secure that application. The scope of this tutorial is to:

  • Only authorized user should be able to access edit employee screen.
  • Unauthorized users should be presented with login screen.
  • Successful credentials should forward to edit employee screen.
  • Unsuccessful credentials should forward to access denied screen.
  • There should be a link for logout of the application.

2. Spring security maven dependencies

Lets start with very first step i.e. update the project dependencies. It will add following four sub-modules in demo for following reasons:

  1. spring-security-core : It contains core authentication and access-control classes and interfaces.
  2. spring-security-web : It contains filters and related web-security infrastructure code. It also enable URL based security which we are going to use in this demo.
  3. spring-security-config : It contains the security namespace parsing code. You need it if you are using the Spring Security XML file for configuration.
  4. spring-security-taglibs : It provides basic support for accessing security information and applying security constraints in JSPs.
<properties>
    <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>

<!-- Spring Security -->
<dependency>
	<groupid>org.springframework.security</groupid>
	<artifactid>spring-security-core</artifactid>
	<version>${org.springframework.version}</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupid>org.springframework.security</groupid>
	<artifactid>spring-security-web</artifactid>
	<version>${org.springframework.version}</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupid>org.springframework.security</groupid>
	<artifactid>spring-security-config</artifactid>
	<version>${org.springframework.version}</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupid>org.springframework.security</groupid>
	<artifactid>spring-security-taglibs</artifactid>
	<version>${org.springframework.version}</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>

Now use “mvn compile” command to update the dependencies in project.

3. Configure DelegatingFilterProxy in web.xml

Spring Security’s web infrastructure is based entirely on standard servlet filters. These filters are defined in web.xml file or they will be ignored by the servlet container.

In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring’s rich dependency-injection facilities and lifecycle interfaces. Spring’s DelegatingFilterProxy provides the link between web.xml and the application context.

<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>

If you are not using any explicit filter definitions and wants spring to configure basic infrastructure for you, then use filter name as ‘springSecurityFilterChain‘ as in above example. Note that you should not use this bean name yourself. Once you’ve added this to your web.xml, you’re ready to start editing your spring security configuration file. Web security services are configured using the element.

Also do not forget to put security configuration file in context config location setting.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    	/WEB-INF/employee-servlet.xml
    	/WEB-INF/application-security.xml
    </param-value>
</context-param>

A complete web.xml file will look like this:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    
  <display-name>Archetype Created Web Application</display-name>
  	<welcome-file-list>
  		<welcome-file>/WEB-INF/index.jsp</welcome-file>
  	</welcome-file-list>
  	
  	<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>
    <servlet>
        <servlet-name>employee</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>employee</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>
	    	/WEB-INF/employee-servlet.xml
	    	/WEB-INF/application-security.xml
	    </param-value>
	</context-param>
    <listener>
	    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

4. Configure login logout security

As we learned in last section that using filter name as springSecurityFilterChain can help you configure the basic infrastructure using element. Lets see how it is configured first? I have written a basic configuration for this demo:

<?xml version="1.0" encoding="UTF-8"?>
<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"  use-expressions="true">
		<intercept-url pattern="/login" access="permitAll" />
		<intercept-url pattern="/logout" access="permitAll" />
		<intercept-url pattern="/accessdenied" access="permitAll" />
		<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
		<form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied" />
		<logout logout-success-url="/logout" />
	</http>

	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<user-service>
				<user name="lokesh" password="password" authorities="ROLE_USER" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

</beans:beans>

Lets see what this configuration actually mean.

  • http : Include configuration related url level security. This element is the parent for all web-related namespace functionality.
  • auto-config : Includes some basic services. It is shorthand for –
    <http>
        <form-login />
        <http-basic />
        <logout />
    </http>
    
  • use-expressions : It is here to use expressions to secure individual URLs. These expressions can be e.g. hasRole([role]), hasAnyRole([role1,role2]), permitAll, denyAll etc.
  • intercept-url : This will match the requested url pattern from request and will decide what action to take based on access value.
  • form-login: This will come into picture when user will try to access any secured URL. A login page mapped to “login-page” attribute will be served for authentication check. It is spring security login-processing-url.

    If not provided, spring will provide an inbuilt login page to user. It also contains attribute for default target if login success, or login failure due to invalid user/password match.

  • logout: This will help to find the next view if logout is called in application.

I am using XML based user service i.e. I will not go to database for password validation rather I have stored username/password combination in configuration file itself. To use this king of setup, authentication-manager is setup with inline in-built user details service. In more real time applications, this is going to be some user service fetching data from remote database.

5. Spring controller

I will reuse the controller and will add additional mappings and handler methods in controller. These additional URLs are /login, /logout and /accessdenied. The updated controller having all method handlers looks like this:

package com.howtodoinjava.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.howtodoinjava.entity.EmployeeEntity;
import com.howtodoinjava.service.EmployeeManager;

@Controller
public class EditEmployeeController {

	@Autowired
	private EmployeeManager employeeManager;

	public void setEmployeeManager(EmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(ModelMap model) {
		return "login";
	}

	@RequestMapping(value = "/accessdenied", method = RequestMethod.GET)
	public String loginerror(ModelMap model) {
		model.addAttribute("error", "true");
		return "denied";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(ModelMap model) {
		return "logout";
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String defaultPage(ModelMap map) {
		return "redirect:/list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String listEmployees(ModelMap map) {

		map.addAttribute("employee", new EmployeeEntity());
		map.addAttribute("employeeList", employeeManager.getAllEmployees());

		return "editEmployeeList";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addEmployee(
			@ModelAttribute(value = "employee") EmployeeEntity employee,
			BindingResult result) {
		employeeManager.addEmployee(employee);
		return "redirect:/list";
	}

	@RequestMapping("/delete/{employeeId}")
	public String deleteEmplyee(@PathVariable("employeeId") Integer employeeId) {
		employeeManager.deleteEmployee(employeeId);
		return "redirect:/list";
	}
}

6. Spring views

We have now configured our application with security configuration and controller handlers. Its time to write the views which are essentially JSP files. Most important addition in jsp files is login.jsp file.

This file have the form which contains text boxes for username and password field. Lets see how it is written:

6.1. login.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>

<html>
	<body>
		<h1 id="banner">Login to Security Demo</h1>  
		<form name="f" action="<c:url value='j_spring_security_check'/>"
					method="POST">
			<table>
				<tr>
					<td>Username:</td>
					<td><input type='text' name='j_username' /></td>
				</tr>
				<tr>
					<td>Password:</td>
					<td><input type='password' name='j_password'></td>
				</tr>
				<tr>
					<td colspan="2">&nbsp;</td>
				</tr>
				<tr>
					<td colspan='2'><input name="submit" type="submit">&nbsp;<input name="reset" type="reset"></td>
				</tr>
			</table>
		</form>
	</body>
</html>

By default, spring auto generates and configures a UsernamePasswordAuthenticationFilter bean. This filter, by default, responds to the URL /j_spring_security_check when processing a login POST from your web-form. For username field it uses ‘j_username‘ and for password field it uses ‘j_password‘.

On submitting this form, UsernamePasswordAuthenticationFilter will match the username and password as configured in authentication-provider settings in application-security.xml.

6.2. logout.jsp

< % session.invalidate(); %>
You are now logged out!!

<a href="//howtodoinjava.com/spring/spring-security/login-form-based-spring-3-security-example/">go back</a>

This view simply invalidate the session and provide a link to go back to login page.

6.3. denied.jsp

This jsp file will come in user screen when user will try to authenticate with invalid user name and password combinations. It will show the corresponding message as configured in message.properties in your classpath.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
	<body>
	
		<h1 id="banner">Unauthorized Access !!</h1>
	
		<hr />
	
		<c:if test="${not empty error}">
			<div style="color:red">
				Your fake login attempt was bursted, dare again !!<br /> 
				Caused : ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
			</div>
		</c:if>
	
		<p class="message">Access denied!</p>
		<a href="//howtodoinjava.com/spring/spring-security/login-form-based-spring-3-security-example/">Go back to login page</a> 
	</body>
</html>

7. Spring security login form demo

Its time to test the application. Simply deploy the application in any server e.g. in my case i am using Tomcat 7.0. Now, do following steps:

7.1. Type the URL in browser “http://localhost:8080/Spring3HibernateIntegration”

It will bring the login screen as besides /login, /logoutand /accessdenied all other URLs are protected URLs.

default-login-screen-spring-security
Default login screen

7.2. Try to authenticate with username ‘demo’ and password ‘1234’

unauthorized-access-spring-security
Unauthorized access for invalid username and password

It will given access denied error because username and password is invalid.

7.3. Try to authenticate with username ‘lokesh’ and password ‘password’

employee-management-screen
Edit employee screen on successful authentication

It will given employee management screen because username and password is correct.

7.4. Click on logout link

logout-spring-security
Logout message

User will be logged out and login screen will appear.

I hope this spring mvc login example has been able to put some light on basic spring security mechanism using xml configurations. If you any question on this Spring security login form example, drop me a comment.

Download sourcecode

Happy Learning !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

72
Leave a Reply

This comment form is under antispam protection
39 Comment threads
33 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
36 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
RJ

Can you suggest me how to connect database table for login access with username & password


<?xml version="1.0" encoding="UTF-8"?>
<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"  use-expressions="true">
		<intercept-url pattern="/login" access="permitAll" />
		<intercept-url pattern="/logout" access="permitAll" />
		<intercept-url pattern="/accessdenied" access="permitAll" />
		<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
		<form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied" />
		<logout logout-success-url="/logout" />
	</http>

	<authentication-manager alias="authenticationManager">
		<authentication-provider>
			<user-service>
				<user name="lokesh" password="password" authorities="ROLE_USER" />
			</user-service>
		</authentication-provider>
	</authentication-manager>

</beans:beans>

Vote Up0Vote Down  Reply
10 months ago
Lokesh Gupta

Try code given in this link for custom user details service.

Vote Up0Vote Down  Reply
10 months ago
RJ

retrieve username & password from database and authorize to login access

Vote Up0Vote Down  Reply
10 months ago
RJ

how to do check login credentials using the database like employee table

Vote Up0Vote Down  Reply
8 months ago
SRAVAN KUMAR

Which IDE is used to import this source code.

Vote Up0Vote Down  Reply
10 months ago
Lokesh Gupta

Code is built with Eclipse.

Vote Up0Vote Down  Reply
10 months ago
SRAVAN KUMAR

HTTP Status 404 – Not Found

Type Status Report

Message /Spring3.2.5Hibernate4.0.1Integration/

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/9.0.12

Vote Up0Vote Down  Reply
10 months ago
Lokesh Gupta

This path looks bad to me. Please download the sourcecode and run as it is given in last section.

Vote Up0Vote Down  Reply
10 months ago
SRAVAN KUMAR

Where can I find SQL dump file to import data?

Vote Up0Vote Down  Reply
10 months ago
Lokesh Gupta

Everything needed to run the demo is in the sourcecode attached to end of the article.

Vote Up0Vote Down  Reply
10 months ago
farhan

Hi Lokesh,
Fine explanation. Great work. I want to know what is the use of ${sessionScope[“SPRING_SECURITY_LAST_EXCEPTION”].message} in denied.jsp page.

Vote Up0Vote Down  Reply
1 year ago
Lokesh Gupta

This link has all such constant values. Follow each constant link to read about them.

https://docs.spring.io/spring-security/site/apidocs/constant-values.html

e.g. If authentication fails, the resulting AuthenticationException will be placed into the HttpSession with the attribute defined by SPRING_SECURITY_LAST_EXCEPTION_KEY.

Vote Up0Vote Down  Reply
1 year ago
saurabh

Hi Lokesh,
this article is very helpful for beginers. Thanks for writing.

Vote Up0Vote Down  Reply
2 years ago
Sidharth

Hi Lokesh ,
Thank you for the nice article explained beautifully with such an ease.
waiting for “SpringBoot” ,kindly write on it,asap.
thank you.

Vote Up0Vote Down  Reply
3 years ago
GopiChnad

what is the Difference between Spring Security and Spring AOP .we can also provide security through AOP . which one is Reliable

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

Spring AOP and Security – both are entirely different things for different purposes. Yes, it’s possible to use AOP for some of security features. Regarding reliability, as I said both are different things and should not be compared.

http://projects.spring.io/spring-security/
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

Vote Up0Vote Down  Reply
3 years ago
KETAN GINOYA

HI LOKESH,

I WANT TO KNOW HOW TO USE INPUT VALIDATION IN THE FORM FIELDS IN JSP WITH THE HELP OF SPRING SECURITY FRAMEWORK.

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

Spring security is for server side, and that’s how it should be used. For only input validation, I suggest to use jQuery.
Though you can use it for other things in JSP : https://howtodoinjava.com/spring-security/spring-security-at-view-layer-using-jsp-taglibs/

Vote Up0Vote Down  Reply
3 years ago
Praveen

Hi Lokesh,

After entering the credentials user name:”lokesh” password:”password” and submit.

I am getting following error,I am using Jboss 6.4 server.

JBWEB000065: HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

JBWEB000309: type JBWEB000066: Exception report

JBWEB000068: message Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

JBWEB000069: description JBWEB000145: The server encountered an internal error that prevented it from fulfilling this request.

JBWEB000070: exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
JBWEB000071: root cause

org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection
org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:596)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)

Kindly let me know what is the issue.

Thanks & Regards,
Praveen

Vote Up0Vote Down  Reply
4 years ago
kamal kumar

HTTP Status 404 – /Spring3HibernateIntegration/

——————————————————————————–

type Status report

message /Spring3HibernateIntegration/

description The requested resource is not available.

——————————————————————————–

Apache Tomcat/7.0.55

i am getting this error. Can you help me out?

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

Please check the generated files in classes folder.

Vote Up0Vote Down  Reply
4 years ago
Deepak

Could you please let me know how we can developed password reset functionality in this example? Your fast inputs are appreciated.

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

I will need to work on it.

Vote Up0Vote Down  Reply
4 years ago
Chaitanya

Hi Lokesh, Thanks for the tutorials.
I am facing one issue though. As soon as I try to login via the custom login page, I always get redirected back to the same login page regardless of entering the correct or incorrect login for the following configuration:

I am using spring 3.2 and have included Spring security 3.2.6 Release jars in the classpath.

However when I try to use inbuilt login page, it seems to be working fine in case of valid and invalid credentials for the following configuration:

Can you please suggest what might be wrong.

Following is my complete web.xml

<!–

–>

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

In comment box, please put your code inside [java] … [/java] OR [xml] … [/xml] tags otherwise it may not appear as intended.

Vote Up0Vote Down  Reply
4 years ago
prateek

Thanks for very nice example. It’s working perfectly even with all current latest dependencies

Vote Up0Vote Down  Reply
4 years ago
Pritam

HI Lokes Thanks for your Example.

My question is when user add the employee button it will call the /add method of controller.Is this restricted by sequrity filter
or not.How to get which user is call the /add url.

please explain it.
Thanks in advance.

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

Right now application is secured only through login page. Once authenticated user can perform any action inside application. To add action specific security, use method level security.

Vote Up0Vote Down  Reply
4 years ago
test

Hi Lokesh,
Though I’ve created Employee table in DB, I’m getting following error. Could you please guide?

org.hibernate.MappingException: Unknown entity: from employee
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
at org.hibernate.impl.SessionImpl.getOuterJoinLoadable(SessionImpl.java:1731)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1697)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
at com.spring.security.dao.EmployeeDaoImpl.getAllEmployees(EmployeeDaoImpl.java:28)
at com.spring.security.service.EmployeeManagerImpl.getAllEmployees(EmployeeManagerImpl.java:27)

Vote Up0Vote Down  Reply
4 years ago
PA

Hello – I’m getting the following error. Could anyone please guide me?

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘test.employee’ doesn’t exist

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

Have you created “test” database with Employee table in it? Error is suggesting that you have not. Please verify.

In this application, you don’t need db access. Please share the modifications you did.

Vote Up0Vote Down  Reply
4 years ago
wiem

CREATE TABLE `employee` (
`ID` INT(5) NOT NULL AUTO_INCREMENT,
`FIRSTNAME` VARCHAR(50) NULL DEFAULT NULL,
`LASTNAME` VARCHAR(50) NULL DEFAULT NULL,
`EMAIL` VARCHAR(50) NULL DEFAULT NULL,
`TELEPHONE` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`ID`)
)
COLLATE=’latin1_swedish_ci’
ENGINE=InnoDB
;

Vote Up0Vote Down  Reply
6 months ago
Gaurav

I am getting below error.Please do the needful at earliest

Can not find the tag library descriptor for “http://www.springframework.org/tags”
Can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core”

Vote Up0Vote Down  Reply
4 years ago
PA

Gaurav – Please try to update project by doing “Maven Update”. Also please check JSTL maven dependency is present or not?

Vote Up0Vote Down  Reply
4 years ago
Gene

Well, I thank you for your sample website, but 90% of the spring websites out there use css, images, and js folders. Since the security namespace affects their access it becomes tricky to resolve. But I figured out what to do. In application-security.xml I had to add these 3 lines:

<intercept-url pattern="/css/**" filters="none"/>
<intercept-url pattern="/images/**" filters="none"/>
<intercept-url pattern="/js/**" filters="none"/>

So I don’t say you Must put them, but it would be helpful if it was put.

-Gene

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

Thanks for your contribution to this page and sharing your solution.

Vote Up0Vote Down  Reply
5 years ago
Gene

Sorry, I did not include the code properly.
Here it is:


In login.jsp :

......

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

Please post code inside [xml] … [/xml] tags.

Vote Up0Vote Down  Reply
5 years ago
Gene

Hi, I downloaded and ran this sample app successfully. However, after I added the security part into my existing “non-secure” Spring MVC project it screwed up with access to CSS and Images paths, so I can’t see CSS and Images on my pages. Here is my configuration for them:

And this is from my existing login.jsp:

….
So some conflict happened with the context, I guess. Do you know how to fix it? Thank you.

Vote Up0Vote Down  Reply
5 years ago
sanjay

i am getting the below error on hitting the login key

HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

Vote Up0Vote Down  Reply
5 years ago
sanjay

sorry i did not see the below post,let me try the same

Vote Up0Vote Down  Reply
5 years ago
Manu

Hi Lokesh,

I am getting this error below. Do we need to setup the local db before running the project.

“HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection”

Regards
Manu

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

Yes you should have one local setup. OR create an in-memory database using info from here : https://howtodoinjava.com/hibernate/hibernate-4-using-in-memory-database-with-hibernate/

Vote Up0Vote Down  Reply
5 years ago
Rafael Nanes

Thanks man!! Very nice tutorial, all the steps worked perfectly.

Vote Up0Vote Down  Reply
5 years ago
narasimhulu

spring security login and registration with database source code …please send me sir…Lokesh Gupta.

Vote Up0Vote Down  Reply
5 years ago
nokz

thank you very much for the example….was very helpful to clear up many stuff……!!!!

Vote Up0Vote Down  Reply
5 years ago
Rakesh

Thank you very much for the useful example. I have one question. Is there any possible to add the user in user_service at run time? if yes, how could we?

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

It is basically example with help of in-memory “authentication-provider”. If user’s list is going to increase the use any custom authentication provider.

https://howtodoinjava.com/spring/spring-security/custom-userdetailsservice-example-for-spring-3-security/

Vote Up0Vote Down  Reply
5 years ago
Rakesh

Lokesh, Thank you very much

Vote Up0Vote Down  Reply
5 years ago
Khushboo Shah

I have a requirement to secure REST services with basic authentication and the web pages, when accessed by browser via Form based authentication.I am trying to combine both of them with Spring-Security-3.2..I read the docs and am trying to follow it , but am not able to configure the spring-context.xml properly..While deploying I get the following errors, Can anyone give me an example of the spring-context.xml.

Caused By: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: No AuthenticationEntry Point could be established. Please make sure you have a login mechanism configured through the namespace (such as form-login) or s pecify a custom AuthenticationEntryPoint with the ‘entry-point-ref’ attribute Offending resource: class path resource [/security-context.xml] at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:72) at org.springframework.security.config.http.AuthenticationConfigBuilder.selectEntryPoint(AuthenticationConfigBuilder.java: 520) at org.springframework.security.config.http.AuthenticationConfigBuilder.createExceptionTranslationFilter(AuthenticationCon figBuilder.java:416) Truncated. see log file for complete stacktrace >

Your help is very much appreciated

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

I do not have a handy example at this time and will plan to build one such in future. But, in my understanding, this should be done inside SecurityInterceptor. There you should try to find out whether client is java client or NBI (non-browser interface) client. Decision can be based on some parameters or simply request headers. Once client type is determined, handle it accordingly (e.g. for browser based check existing session etc).

Vote Up0Vote Down  Reply
5 years ago
indra sam

Good tutorial, however how to add user management, roles and passwords with a web interface. please if have a reference. thank you.

Vote Up0Vote Down  Reply
5 years ago
venkatramulu

thank u very much lokesh…….. provided lots of information regarding logine with spring security…. thankq

Vote Up0Vote Down  Reply
5 years ago
arso

Thanks for the tutorial! Is this tutorial Spring 4.0 compliant? Will any changes have to be made to use Spring 4.0.

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

I ma not sure but backward compatibility must have been preserved.

Vote Up0Vote Down  Reply
5 years ago
Ranga

helpful example – /** did the trick for me in the security URL interception

Vote Up0Vote Down  Reply
5 years ago
Jayakumar Jayaraman

Hi Lokesh

Nice post.
I have an existing web application build on Primefaces, EJB and without Spring. Will I be able to integrate spring security 3.2 to this existing application ?

Thanks
Jay

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

Definitely yes. Spring provides seamless integration with all major frameworks including primefaces. Go through some information listed here: https://www.google.co.in/search?q=Primefaces+with+spring+security

Vote Up0Vote Down  Reply
5 years ago
Venkata Sriram

Hi sir,i wrote similar kind of security-context.xml file,iam getting the following error:

cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘http’.

all 4 jars(core,web,context,taglibs) are added to project sir.

Thanks
Venkata Sriram

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

Make sure you have used correct namespace definitions:

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“

Vote Up0Vote Down  Reply
5 years ago
shivayan

Thanks for the tutorial. However i have a couple of queries. First one, on startup how is it getting redirected to the login page? Secondly,on page submission how does these ‘j_spring_security_logout’ or ‘j_spring_security_check’ work??

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

I mentioned it already: By default, spring auto generates and configures a UsernamePasswordAuthenticationFilter bean. This filter, by default, responds to the URL /j_spring_security_check when processing a login POST from your web-form. For username field it uses ‘j_username‘ and for password field it uses ‘j_password‘.

Vote Up0Vote Down  Reply
5 years ago
Saurabh

I am getting the following error on adding springSecurityFilterChain (DelegatingFilterProxy) in web.xml

SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘springSecurityFilterChain’ is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1097)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:236)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:107)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4746)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5399)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Dec 08, 2013 1:16:08 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error filterStart
Dec 08, 2013 1:16:08 PM org.apache.catalina.core.StandardContext startInternal

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

Reason seems to be that /WEB-INF/application-security.xml is not loaded at runtime. Make sure it is present in .war file (or target folder).

Vote Up0Vote Down  Reply
6 years ago
Deepu James

Great tutorial and it works perfect. However my doubt is won’t spring security support special characters in username? I need to use my email as username but it throws error…!!

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

Need to check

Vote Up0Vote Down  Reply
6 years ago
Karthi

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [java.empcontroller.EditEmployeeController] for bean with name ‘editEmployeeController’ defined in file [D:karthikaSpring Workspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebappsSpringSecurityWebApplnWEB-INFclassesjavaempcontrollerEditEmployeeController.class]; nested exception is java.lang.ClassNotFoundException: java.empcontroller.EditEmployeeController

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

Exception is self explanatory. Class not found. Look into your classes folder if it is generated. By the way, having package name starting with “java”— I will not recommend this. This is used for JDK supplied classes. Compiler will not prevent you, but you really should not use this.

Vote Up0Vote Down  Reply
6 years ago
nani

here where is the employee entity and employee manager classes

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

Please download the sourcecode.

Vote Up0Vote Down  Reply
6 years ago
Abida

Hello,
I just have a query tat where are we comparing the database password and password given in JSP..??

Vote Up0Vote Down  Reply
6 years ago
Luis Eyzaguirre

Thank you very much for you example!!!

Vote Up0Vote Down  Reply
6 years ago

Search Tutorials

Spring Security Tutorial

  • Security – Introduction
  • Security – Method Level Security
  • Security – Siteminder
  • Security – Login Form
  • Security – JSP taglibs
  • Security – jdbc-user-service
  • Security – UserDetailsService
  • Security – Basic Auth
  • Security – Junit Tests
  • @PreAuthorize and @Secured

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz