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 :
- 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.
- 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.
- 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:security="http://www.springframework.org/schema/security" 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.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <security:http auto-config="true"> <security:intercept-url pattern="/index*" access="ROLE_USER" />; </security:http> <security:authentication-manager> <security:authentication-provider> <security:user-service> <security:user name="dineshonjava" password="sweety" authorities="ROLE_USER" />; </security:user-service> </security:authentication-provider> </security:authentication-manager> </beans>
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.
- <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.
- <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.
- <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
- Spring Security Interview Questions and Answers
- Spring Security Java Based Configuration with Example
- Spring Security XML Namespace Configuration Example
- Spring Security XML Based Hello World Example
- Spring Security form-based login example
- Spring Security Login Form Based Example Using Database
- Spring Security Authentication Example Using HTTP Basic
- Spring Security Authorized Access Control Example
- Spring Security Customized Access Denied Page
- Spring Security Custom Error Message
- Spring Security Logout Example
- Spring Security Fetch Logged in Username
- Spring Security Password Hashing
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.
Hi Siva,
Thanks for nice comment and we will add two missing jars as soon as possible.
Thanks,
Dinesh
Thanks Dinesh. Nice post.
Thanks Mahes!!!!!
you have to take a closer look at your depedencies.
You are currently pooling in to many dependencies. Use maven!
thank you so much
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..
Hi Mahendra,
It may some problem in deploy your application.
Plz change your workspace and redeploy again.
Thanks,
Dinesh
Mahendra Bagul please add commons-logging and jstl.jar file its relate to logger error.