Spring Security Basic Example

Spring security is one of the robust security framework provided by Spring community. It is very easy and simple to configure the set up. Spring security has been released its first version on 2003, over the period of years it has become more matured and defacto standard for the spring applications. All the spring web applications uses spring security to beef up their environmental configurations. This article explains the very simple example for configuring the spring security for your web application. I will write the series of articles on spring security with different features like using the databases, etc. in my future articles.To complete this example, you need to write the following components:

  • mvc-dispatcher-servlet.xml
  • spring-security.xml
  • web.xml
  • ExampleController.java
  • basics.jsp
  • login.jsp

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 org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(&amp;quot;/basics&amp;quot;)
public class ExampleController {
  @RequestMapping(method = RequestMethod.GET)
  public String printWelcome(ModelMap model) {
     model.addAttribute(&amp;quot;message&amp;quot;, &amp;quot;Spring Security Basic Example&amp;quot;);
     return &amp;quot;basics&amp;quot;;
  }

}

basics.jsp

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

2. Spring Security Configuration

In the below code, authentication-provider is the type of authentication done or used by the application. One can configure more than one authentication-provider under authentication-manager. To make this clear, you may configure the different type of authentications using database, LDAP, properties file, etc. in the same authentication-manager. user-service is the reference for the data storage implementation.

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" />
	</http>

	<authentication-manager>
	  <authentication-provider>
	    <user-service>
		<user name="Hello" password="Pass" 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 retrieved 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.

<%@ 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>Insert title here</title>
</head>
<body>
<form method="POST" name="loginform" action="j_security_check">
    <table style="vertical-align: middle;">
        <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><input type="submit" value="Login" /></td>
        </tr>
    </table>
    </form>
    <hr>
    <form method="POST" name="loginform" action="j_negotiate_check">
    <input type="submit" value="Login w/ Current Windows Credentials" />
    </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>

spring-security-1

I hope this example would have provided basic idea on configuring the spring security for your web applications. In my next articles I would write about the detailed configurations using the spring security.

Besides the Spring Security mentioned here, though unrelated, maybe visit this camera’s website if you get a second.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!