Spring Security hello world example

In this tutorial, we will show you how to integrate Spring Security with a Spring MVC web application to secure a URL access. After implementing Spring Security, to access the content of an “admin” page, users need to key in the correct “username” and “password”.

Technologies used :

  1. Spring 3.2.8.RELEASE
  2. Spring Security 3.2.3.RELEASE
  3. Eclipse 4.2
  4. JDK 1.6
  5. Maven 3
Note
Spring Security 3.0 requires Java 5.0 Runtime Environment or higher

1. Project Demo

2. Directory Structure

Review the final directory structure of this tutorial.

spring-security-helloworld-directory

3. Spring Security Dependencies

To use Spring security, you need spring-security-web and spring-security-config.

pom.xml

	<properties>
		<jdk.version>1.6</jdk.version>
		<spring.version>3.2.8.RELEASE</spring.version>
		<spring.security.version>3.2.3.RELEASE</spring.security.version>
		<jstl.version>1.2</jstl.version>
	</properties>

	<dependencies>

		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<!-- jstl for jsp page -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>

	</dependencies>

4. Spring MVC Web Application

A simple controller :

  1. If URL = /welcome or / , return hello page.
  2. If URL = /admin , return admin page.

Later, we will show you how to use Spring Security to secure the “/admin” URL with a user login form.

HelloController.java

package com.mkyong.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

	@RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
	public ModelAndView welcomePage() {

		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Hello World");
		model.addObject("message", "This is welcome page!");
		model.setViewName("hello");
		return model;

	}

	@RequestMapping(value = "/admin**", method = RequestMethod.GET)
	public ModelAndView adminPage() {

		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Hello World");
		model.addObject("message", "This is protected page!");
		model.setViewName("admin");

		return model;

	}

}

Two JSP pages.

hello.jsp

<%@page session="false"%>
<html>
<body>
	<h1>Title : ${title}</h1>	
	<h1>Message : ${message}</h1>	
</body>
</html>
admin.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<body>
	<h1>Title : ${title}</h1>
	<h1>Message : ${message}</h1>

	<c:if test="${pageContext.request.userPrincipal.name != null}">
	   <h2>Welcome : ${pageContext.request.userPrincipal.name} 
           | <a href="<c:url value="/j_spring_security_logout" />" > Logout</a></h2>  
	</c:if>
</body>
</html>
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.mkyong.*" />

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

5. Spring Security : User Authentication

Create a Spring Security XML file.

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.2.xsd">

	<http auto-config="true">
		<intercept-url pattern="/admin**" access="ROLE_USER" />
	</http>

	<authentication-manager>
	  <authentication-provider>
	    <user-service>
		<user name="mkyong" password="123456" authorities="ROLE_USER" />
	    </user-service>
	  </authentication-provider>
	</authentication-manager>

</beans:beans>

It tells, only user “mkyong” is allowed to access the /admin URL.

6. Integrate Spring Security

To integrate Spring security with a Spring MVC web application, just declares DelegatingFilterProxy as a servlet filter to intercept any incoming request.

web.xml

<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Spring MVC Application</display-name>

	<!-- Spring MVC -->
	<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>

        <!-- Loads Spring Security config file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-security.xml
		</param-value>
	</context-param>

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

7. Demo

That’s all, but wait… where’s the login form? No worry, if you do not define any custom login form, Spring will create a simple login form automatically.

Custom Login Form
Read this “Spring Security form login example” to understand how to create a custom login form in Spring Security.

1. Welcome Page – http://localhost:8080/spring-security-helloworld-xml/welcome

spring-security-helloworld-welcome

2. Try to access /admin page, Spring Security will intercept the request and redirect to /spring_security_login, and a predefined login form is displayed.

spring-security-helloworld-login

3. If username and password is incorrect, error messages will be displayed, and Spring will redirect to this URL /spring_security_login?login_error.

spring-security-helloworld-login-error

4. If username and password are correct, Spring will redirect the request to the original requested URL and display the page.

spring-security-helloworld-admin

Download Source Code

Download it – spring-security-helloworld-xml.zip (9 KB)

References

  1. Spring Security Official Site
  2. Spring 3 MVC hello world example
  3. Spring Security form login example (authentication)
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
madhavi
Guest
madhavi

This is very confusing , i can’t run the application , Couldn’t able to identify the where is the problem also.
Can anyone help me how exactly you created the code for this?

bhusahn
Guest
bhusahn

same here

Surendra
Guest
Surendra

its simple create one extra xml and add security code in it, then write in web.xml and it will work as run the project.

abdul hafiz
Guest
abdul hafiz
Marten
Guest
Marten

Your configuration is flawed, you are duplicating bean instances. Both the ContextLoaderListener and DispatcherServlet load the ‘/WEB-INF/mvc-dispatcher-servlet.xml’ configuration. Which basically leads to scanning the classpath twice, 2 InternalViewResolvers etc.

In this case it doesn’t lead to problems but for larger projects it will lead to problems.

Amar
Guest
Amar

Hi Martin,

Can you explain a bit more on the issue, you mentioned above ? and what is the solution for that ?

mkyong
Guest
mkyong

Thanks, article is updated.

rafeeq
Guest
rafeeq

For a basic token based authentication use the below, This is based on Spring 3.1

yasser
Guest
yasser

if you add the / at the end of the url… i.e “http://localhost:8080/SpringMVC/welcome/” …. I don’t get the login form instead it shows the hell.jsp which is protected resource.

vijay
Guest
vijay

I am also facing same problem

Raheel
Guest
Raheel

Thanks for this tutorial
Can you give us examples of using annotations in spring security i.e. @secured @preauthorize etc

Vicky
Guest
Vicky

Some issues while execution:

– url http://localhost:8080/SpringMVC/welcome doesn’t automatically redirect to /welcome after authentication. It becomes http://localhost:8080/SpringSecuritySetup/;jsessionid=D8669208493AFDE7D9E113FEDCB554CF where I need to insert /welcome manually, then it shows next page!!! Why so?

– Since this project is using old jars, I updated to 3.2.3 and spring-security jars to 3.1 Then it didn’t work. Login page came but authentication never succeed even after providing correct credentials. You can see the complete post here:
http://www.coderanch.com/t/618591/Spring/Spring-security-sample-working

Waiting for the reply. Thanks.

Vicky
Guest
Vicky

Please ignore the context root ‘SpringSecuritySetup’ as I renamed the project.

David
Guest
David

hi,when download the source code,it give No bean named ‘springSecurityFilterChain’ is defined ,can you help me

Adriano Moreira
Guest
Adriano Moreira

whats name the folder with files xml ?
Webapp –> WEB – INF ?

?????? ????
Guest
?????? ????

Hello. First of all I have to say thank you for yours great tutorials and complete explanations for them. Most of my recent experience with modern JAVA technologies and frameworks received from this blog. But now I got a trouble trying to use Spring Security with Spring MVC aplication. The issue is with new versions of Spring/Spring Security. I am using Spring framework version 4.1.6.RELEASE and trying to add Security version 4.1.0.RC1. And they are conflicting wtih each other, It says that no servlet alowed together in conjunction with org.springframework.web.context.ContextLoaderListener. Your tutorial works fine, but it is with versions 3.2.8… Read more »

trackback
Spring Security form login example

[…] provided, Spring Security will create a simple login form automatically, see demonstration in this Spring Security hello world example.In this tutorial, we show you how to create a custom login form and ask Spring Security to use it […]

Michael
Guest
Michael

Very nice, clean Spring Security tutorial. Much of the stuff out there is just too hard to follow. This one isn’t. Thanks!

habou
Guest
habou

Thank you very much my Professor

Can you add the database connection configuration with Spring Security !!!??

trackback
ClassNotFoundException : DefaultSavedRequest

[…] DefaultSavedRequest is inside spring-security-web.jar. Visit this Spring Security hello world example for the list of dependencies libraries. <!– Spring Security & dependencies –> […]

trackback
Spring Security access control example

[…] page.1. Project DependenciesAccess control is included in core Spring Security jar. Refer to this Spring Security hello world example for list of the required dependencies.2. Spring MVCSpring MVC controller and return a […]

trackback
Spring Security Tutorials

[…] secure your web application easily.Quick StartSpring Security dependencies and how to configure it.Spring Security hello world example Use Spring security to provide a simple login authentication form to secure URL access in web […]

Jarode
Guest
Jarode

Hello Professor,

I’ve been working in an application using Stuts2 as a dispatcher, when I arrived to fix the security I heard about Spring Security, I’ve tried your tutorials and they was very interesting.

I’m now in a bad situation, cause all the tutorials are using spring as dispatcher and there is no sample using Struts2.
could you please advice me ?
Thanks you very much for you great work

Kind Regards

Somasekhar Reddy
Guest
Somasekhar Reddy

Hi Mkyong,

Thanks for the great and simple applications.
It would be more better, if you provide jar files too, along with source code.

Regards
Sekhar

trackback
» Spring Security hello world example ??? ?? ???
Isaac
Guest
Isaac

Hi, thanks for your effort because this is a great post, for me appears an error:

No mapping found for HTTP request with URI [/com.mkyong.common_SpringMVC_war_1.0-SNAPSHOT] in DispatcherServlet with name ‘mvc-dispatcher’

I have checked the web.xml and it´s exactly as in your example. Then ¿why it doesn´t works for me?

Thanks in advance

avishaygold@gmail.com
Guest
avishaygold@gmail.com

You can add thw welcome property in web.xml :

/WEB-INF/pages/login.jsp
/WEB-INF/pages/login.html

this will load the right jsp
good luck

Marco Tedone
Guest
Marco Tedone

The examples are missing a @Controller annotation on the HelloController class. Add the annotation and everything should work fine.

snail
Guest
snail

thanks a lot

and , if ssh2(struts2 spring3 hibernate3) project add spring security 3,some one will feel better ^!^ cause by I use ssh2 in project and learning…

Sagar R. Kapadia
Guest
Sagar R. Kapadia

Hi Mkyong! Thanks for the superb article. One article I saw elsewhere said it would take days to figure out and use spring security in my own applications. I am very grateful to you

vijayakumar
Guest
vijayakumar

Hi Yonng, it was great article, very simple and stright forward. i am able to run the application sucessfully. but i am having one doubt? when you type the following url

http://localhost:8090/SecurityExample/welcome

i am getting the page with username and password fields. i just wanted to know how this thing happend. we have not mentioned those things anyware in application. can u please clear my doubt if it is very basic also. thank you

Rippon
Guest
Rippon

Vijay,

If you dont define a custom login page,spring security will create one dynamically for you.

Regards,
Rippon

skaj_vikler
Guest
skaj_vikler

I got following exception
SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘springSecurityFilterChain’ is defined

csa_sam
Guest
csa_sam

Same error

Tony
Guest
Tony

Same

DerIngo
Guest
DerIngo

I had the same problem, this fixed it: http://stackoverflow.com/a/12125135

Bharatkumar Patel
Guest
Bharatkumar Patel

Thanks !!! Very nice and easily understandable tutorial. Thanks !!!

John
Guest
John

The best tutorial on a given topic.
Thank you !!!

trackback
Spring Security HTTP basic authentication example

[…] Spring Security hello world example […]

Per Wramdemark
Guest
Per Wramdemark

Hi,
You shouldn’t add /WEB-INF/mvc-dispatcher-servlet.xml to the config for the ContextLoaderListener. It would potential lead to beans getting initialized twice since the same beans will also be initialized from the DispatcherServlet.

Adrien
Guest
Adrien

You want to add “s” to the verbs you conjugate at the 3rd person.

In your first sentence: Spring Security allowS developer to integrate security features with J2EE web application easily, it highjackS incoming HTTP request via servlet filters, and implementS “user defined” security checking.

That’s 3 you forgot in one sentence. I’ve seen that on many tutorials and thought I’d let you know 🙂

Thanks for the tutorials and keep up the good work 🙂

Dundar
Guest
Dundar

Hi yong…

My English so bad… So, I am sorry…

I have a problem…

I import the project to eclipse… But I take error (about “kind4”) So, I exist the similar maven project on eclipse (eclipse juno)… I run it on server(Apache Tomcat) I take error (the following)…

No mapping found for HTTP request with URI [/com.mkyong.common_SpringMVC_war_1.0-SNAPSHOT/] in DispatcherServlet with name ‘mvc-dispatcher’

Navin Bansal
Guest
Navin Bansal

nice and easy to understand…thanx for post