Spring Security Login Form Example

SHARE & COMMENT :

In my previous post I have written a very simple spring security example without any login form mechanism. This example has the slight modification to include the login form example for the authentication. The changes are reflected in the spring-security.xml file. If the user is not logged in, the request will be redirected to the login page which is configured in the spring-security.xml file. If the authentication is failed then it would redirect to the failure pages. This is the slight advanced from the previous article. If you have any questions, please write it in the comments section.

1. Spring MVC Configuration

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	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/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:component-scan base-package="com.spring.security.controller" />

	<bean
	  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	  <property name="prefix">
		<value>/WEB-INF/pages/</value>
	  </property>
	  <property name="suffix">
		<value>.jsp</value>
	  </property>
	</bean>

</beans>

ExampleController.java

package com.spring.security.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 ExampleController {

	@RequestMapping(value="/basics", 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 "basics";
	}

	@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";
	}
}

basics.jsp

<html>
<body>
	<h1>Message : ${message}</h1>
</body>
</html>

2. Spring Security Configuration

form-login element is used for configuring the login form for the application. It has the attributes login-page, default-target-url and authentication-failure-url. As the name of the attribute itself implies the purpose, it is very easy to understand for you. Whatever the URL you have configured in the file will be used while user access the application. logout element is configured to redirect the user once the logout action is preformed.

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="/basics*" access="ROLE_USER" />
		<form-login login-page="/login" default-target-url="/basics"
			authentication-failure-url="/loginfailed" />
		<logout logout-success-url="/logout" />
	</http>

	<authentication-manager>
	  <authentication-provider>
		<user-service>
			<user name="Spring" password="spring" authorities="ROLE_USER" />
		</user-service>
	  </authentication-provider>
	</authentication-manager>
</beans:beans>

login.jsp

It is very important to understand the variables used in this JSP file. The variables used in the page j_security_check, j_negotiate_check, j_username and j_password are predefined variables in the spring security framework. If you modify the variable names, the application will not work. Our application is configured in such a way that when user is not logged in, the first request will be forwarded to the login.jsp. Once user enters the user name and password, the values are retrived by spring security and validates against the correct values from the authentication-provider. The real beauty is that, all the work is handled by the framework itself, we are not writing any extra code.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body onload='document.f.j_username.focus();'>
	<h3>Login with Username and Password (Spring Security Example)</h3>
	${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

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

3. Spring Security and Spring MVC Integration

web.xml

<?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>Spring MVC Application</display-name>
  <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>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
			/WEB-INF/mvc-dispatcher-servlet.xml,
			/WEB-INF/spring-security.xml
		</param-value>
  </context-param>
  <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>

I hope this article provided few more information on configuring the login form using the spring security. If you have any questions, please post it in the comments section. In my next article, I will write about configuring the database to authenticate the user. Please subscribe here to receive the future articles.

For other types of security unrelated to the Spring Security Login Form, if you get a second, note this other site carries numerous security related equipment for the home or your business. You can see their website here Security Cameras. For other informative security data, also look at this security website.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Nice blog. I have found following blog useful as well
    http://www.srccodes.com/p/article/35/spring-security-custom-login-form-example

  2. Thanks for sharing this example. Also if you have time, take a look at my blog. It is also tutorials in Java. http://javapointers.com

Trackbacks

  1. [...] my earlier articles I have written about the basic spring security mechanism and how to use the login form to redirect the users. Before jumping on to the advanced details on spring security, lets learn [...]

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better