Spring Security Hello World Example

In this tutorial we will show you the way to configure Spring Security with Spring MVC web application to secure mvc pages. We will take an spring mvc web application example in which, we will configure Spring Security to protect a page from outside access.

Spring Security allows to you to integrate security features with J2EE web application easily, it take care about all incoming HTTP requests via servlet filters, and implements "user defined" security checking.

In this tutorial, we show you how to integrate Spring Security 3.0 with Spring MVC3 web application to secure URL access. After implemented Spring security, to view the content of the page, users need to key in correct “username” and “password”.


Required Tools used for this Application:

  • Spring MVC 3.0.1
  • Spring Security 3.1.0
  • STS 2.8.1.RELEASE
  • Tomcat 7
  • Jdk 1.7
To understand this application you have some prior knowledge about the Spring MVC web application.

In this tutorial, there is an example of Hello World page that is managed by Spring MVC framework. We will configure Spring Security in this example and will make the
Hello World page secure. User have to authenticate user to view Hello World page.


Step 1: Please download the following more jars for Spring Security Lib from its official site.
  • spring-security-acl-3.1.3.RELEASE.jar
  • spring-security-aspects-3.1.3.RELEASE.jar
  • spring-security-cas-3.1.3.RELEASE.jar
  • spring-security-config-3.1.3.RELEASE.jar
  • spring-security-core-3.1.3.RELEASE.jar
  • spring-security-crypto-3.1.3.RELEASE.jar
  • spring-security-ldap-3.1.3.RELEASE.jar
  • spring-security-openid-3.1.3.RELEASE.jar
  • spring-security-remoting-3.1.3.RELEASE.jar
  • spring-security-taglibs-3.1.3.RELEASE.jar
  • spring-security-web-3.1.3.RELEASE.jar
Step 2: Create the project "SpringSecurityHelloExample" with packages "com.dineshonjava.security.controller" and create the "HelloSecurityController.java" file in this package.

Step 3: Some more folders also create on the "WEB-INF" folder with name libs, views for jars and jsp files respectively. Two files "sdnext-servlet.xml" and "sdnext-security.xml" are created on the "WEB-INF" folder.

Step 4: Configuring web.xml for Spring Security


 
  sdnext
  org.springframework.web.servlet.DispatcherServlet
        1
 

 
  sdnext
  *.html
 
 
  
                  org.springframework.web.context.ContextLoaderListener
        
 
 
 
  contextConfigLocation/WEB-INF/sdnext-*.xml,   
 
 
  index.html
 
 
 
 
  springSecurityFilterChain
  
                  org.springframework.web.filter.DelegatingFilterProxy
                
 
 
 
  springSecurityFilterChain
  /*
 
 

In web.xml, we have configured Spring MVC to manage the request came for the URL “*.html”. For configuring Spring Security we do the following :

  1. First of all, we have to register org.springframework.web.filter.DelegatingFilterProxy filter in web.xml. This filter manages the securing of the web pages.
  2. The filter will manage the requested URL “/*”. That means all the requests will go through the filter so that it can authenticate the user of particulate web pages that we will configured as secured pages with Spring Security.
  3. Register org.springframework.web.context.ContextLoaderListener listener provided in Spring so that it can configure spring context on server startup.
Step 5: Creating welcome page (welcome.jsp)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<html>
<head>

<title>WELCOME TO SECURE AREA</title>
</head>
<body>
 

Message : ${message}

Author : ${author}

</body> </html>
Our welcome page is very simple that only shows a message that is stored in model object. The message is provided by the controller class.

Step 6: Creating HelloSecurityController class (HelloSecurityController.java)
package com.dineshonjava.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;

/**
 * @author Dinesh Rajput
 *
 */
@Controller
@RequestMapping("/index")
public class HelloSecurityController {
 
 @RequestMapping(method = RequestMethod.GET)
 public String executeSecurity(ModelMap model) {
 
  model.addAttribute("message", "Spring Security Hello World");
  model.addAttribute("author", "By DineshOnJava.com");
  return "welcome";
 
 }
}

Step 7: Spring Securing Configuration file (sdnext-security.xml)


   
 <security:intercept-url pattern="/index*" access="ROLE_USER" />


    
   
     
  <security:user name="dineshonjava" password="sweety" authorities="ROLE_USER" />
     
   
 



After that we will have to create a Spring Security Configuration file, in which have to define the security constrains that are to be applied to our application. You will see a lot of new things in this file. I will explain all the tags one by one make the things clear to you.

  1. <security:http/> tag is used to define security setting for web application for defining access constrains for pages, defining login pages, login process to use, activate remember me option, customizing session level setting etc. Here we have used only one option i.e.  <security:intercept-url pattern=“/index*” access=“ROLE_USER”/>. <security:intercept-url/> tag is used to define url patterns to be secure and the definition of the roles who can access them.  In our example all url patters have pattern /index* are secured and only user will role ROLE_USER can access the pages.
  2. <security:authentication-manager/> tag is used to define method of authentication of the user on the basis of that user will be able to access a page.
  3. <security:authentication-provider/> tag specifies the username and password provider. It can be also a database table. Here we have used hard coded username and password. Password is "sweety" and username is "dineshonjava".
 Step 8: Spring Configuration File (sdnext-servlet.xml)



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

 
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".jsp" />
 

 


Step 9: Running the example

Export the example as war and deploy it Tomcat 7 server. While browsing the project you will get the following screen for loging:

http://localhost:8080/sdnext/spring_security_login
 

From where is this login page came?  

We have not created it. Actually, this is the default login page provided by Spring Security. We can also customize it to use our own login page. We will see an example also relate to this.

Error messages will be displayed if wrong username and password are provided.
http://localhost:8080/sdnext/spring_security_login?login_error

 If correct username and password are provided, Spring security will redirect to the original requested URL and display the content of the page.
http://localhost:8080/sdnext/
 


Download Source Code + Libs
SpringSecurityHelloExample.zip


References
  1. Spring Security
  2. Spring Security documentation


                             <<previous<<             || index  ||         >>next>>




8 comments:

  1. Hi Dinesh, This is siva. Your doing great job.
    When i downloaded this hello world example and tried to run. I got error. It is missing two jar files: Commons-logging and Jstl jars. After adding these two jars it is working fine. Please add these two jars.

    ReplyDelete
    Replies
    1. Hi Siva,

      Thanks for nice comment and we will add two missing jars as soon as possible.

      Thanks,
      Dinesh

      Delete
  2. you have to take a closer look at your depedencies.
    You are currently pooling in to many dependencies. Use maven!

    ReplyDelete
  3. thank you so much

    ReplyDelete
  4. Hi Dinesh,

    I got this exception when I ran this example. Please help me to solve this problem.

    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/SpringSec1]]

    Thanks in advance..

    ReplyDelete
    Replies
    1. Hi Mahendra,

      It may some problem in deploy your application.
      Plz change your workspace and redeploy again.

      Thanks,
      Dinesh

      Delete