Spring Security

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

<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>
  <servlet-name>sdnext</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>sdnext</servlet-name>
  <url-pattern>*.html</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/sdnext-*.xml,   </param-value></context-param>
 
 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 
 <!-- Spring Security -->
 <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>

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)

<beans xmlns:p="http://www.springframework.org/schema/p" xmlns:>
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)
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

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

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

 
</beans>

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>>
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago