Spring Security Hello World Annotation Example

security

In preview post, we are using XML files to configure the Spring Security in a Spring MVC environment. In this tutorial, we are going to show you how to convert the previous XML-base Spring Security project into a pure Spring annotation project.

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
  6. Tomcat 7 (Servlet 3.x)

Few Notes

  1. This tutorial is using WebApplicationInitializer to load the Spring Context Loader automatically, which is supported in Servlet 3.x container only, for example, Tomcat 7 and Jetty 8.
  2. Since we are using WebApplicationInitializer, the web.xml file is NOT required.
  3. Spring Security annotations are supported in older Servlet 2.x container, for example, Tomcat 6. If you use the classic XML file to load the Spring context, this tutorial is still able to deploy on Servlet 2.x container, for example, Tomcat 6

1. Project Demo

See how it works.

2. Directory Structure

Review the final directory structure of this tutorial.

spring-security-helloworld-annotation-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 3 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.
  3. If URL = /dba , return admin page.

Later, we will secure the /admin and /dba URLs.

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 - Admin Page!");
		model.setViewName("admin");

		return model;

	}

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

		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Hello World");
		model.addObject("message", "This is protected page - Database 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="/logout" />" > Logout</a></h2>  
	</c:if>
</body>
</html>

5. Spring Security Configuration

5.1 Create a Spring Security configuration file, and annotated with @EnableWebSecurity

SecurityConfig.java

package com.mkyong.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
	  auth.inMemoryAuthentication().withUser("mkyong").password("123456").roles("USER");
	  auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
	  auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {

	  http.authorizeRequests()
		.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
		.antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
		.and().formLogin();
		
	}
}

The equivalent of the Spring Security xml file :


	<http auto-config="true">
		<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
		<intercept-url pattern="/dba**" access="ROLE_ADMIN,ROLE_DBA" />
	</http>

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

5.2 Create a class extends AbstractSecurityWebApplicationInitializer, it will load the springSecurityFilterChain automatically.

SpringSecurityInitializer.java

package com.mkyong.config.core;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
   //do nothing
}

The equivalent of Spring Security in web.xml file :


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

6. Spring MVC Configuration

6.1 A Config class, define the view’s technology and imports above SecurityConfig.java.

AppConfig.java

package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.mkyong.web.*" })
@Import({ SecurityConfig.class })
public class AppConfig {

	@Bean
	public InternalResourceViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver 
                          = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/pages/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
	
}

The equivalent of the Spring XML file :


	<context:component-scan base-package="com.mkyong.web.*" />

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

6.2 Create a Initializer class, to load everything.

SpringMvcInitializer.java

package com.mkyong.config.core;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.mkyong.config.AppConfig;

public class SpringMvcInitializer 
       extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { AppConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
	
}

Done.

Note
In Servlet 3.x container environment + Spring container will detect and loads the Initializer classes automatically.

7. Demo

7.1. Welcome Page – http://localhost:8080/spring-security-helloworld-annotation/welcome

spring-security-helloworld-annotation-welcome

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

spring-security-helloworld-annotation-login

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

spring-security-helloworld-annotation-login-error

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

spring-security-helloworld-annotation-admin

7.5. For unauthorized user, Spring will display the 403 access denied page. For example, user “mkyong” or “dba” try to access the /admin URL.

spring-security-helloworld-annotation-403

Download Source Code

References

  1. Spring Security
  2. Spring Security Java Config Preview: Web Security
  3. Hello Spring MVC Security Java Config
  4. Wikipedia : Java Servlet
  5. Wikipedia : Apache Tomcat
  6. Spring Security Hello World XML Example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Chris Linder
Guest
Chris Linder

help WARNING: No mapping found for HTTP request with URI [/SecurityMVC/welcome] in DispatcherServlet with name ‘dispatcher’

Mike H
Guest
Mike H

I had to change two things to get this to work:

Add this to the maven pom.xml (if copying from the web page)…

javax.servlet
javax.servlet-api
3.1.0
provided

The example in the zip file has this except there is a typo: replace ‘provider’ with ‘provided’ in the scope tag.

Secondly, the WAR plug-in doesn’t like not having a web.xml file, so I added this to the config in the pom.xml:

org.apache.maven.plugins
maven-war-plugin

false

After that it worked fine on Tomcat 8 with Java 1.8.

Vishnudev K
Guest
Vishnudev K

why there is no web.xml? When i tried it with web.xml its not working. :(

Loc Le
Guest
Loc Le

auth.inMemoryAuthentication().withUser(“mkyong”).password(“123456”).roles(“USER”);
auth.inMemoryAuthentication().withUser(“admin”).password(“123456”).roles(“ADMIN”);
auth.inMemoryAuthentication().withUser(“dba”).password(“123456”).roles(“DBA”);

How can I using username and password get from database?

Yogesh
Guest
Yogesh

I am getting the following error while executing this porgram:
“getServletConfigClasses() did not return any configuration classes”

Can somebody help me understand this?

Javed
Guest
Javed
I am getting this error.. [ERROR] COMPILATION ERROR : [INFO] ————————————————————- [ERROR] MY-WorkSpacesspring-security-helloworld-annotationssrcmainjavacommkyongconfigcoreSpringSecurityInitializer.java:[5,7] error: cannot access ServletException [ERROR] MY-WorkSpacesspring-security-helloworld-annotationssrcmainjavacommkyongconfigSecurityConfig.java:[12,7] error: cannot access Filter [INFO] 2 errors [INFO] ————————————————————- [INFO] ———————————————————————— [INFO] BUILD FAILURE [INFO] ———————————————————————— [INFO] Total time: 2.371 s [INFO] Finished at: 2017-05-19T15:22:21+05:30 [INFO] Final Memory: 11M/27M [INFO] ———————————————————————— [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project spring-security-helloworld-annotations: Compilation failure: Compilation failure: [ERROR] MY-WorkSpacesspring-security-helloworld-annotationssrcmainjavacommkyongconfigcoreSpringSecurityInitializer.java:[5,7] error: cannot access ServletException [ERROR] MY-WorkSpacesspring-security-helloworld-annotationssrcmainjavacommkyongconfigSecurityConfig.java:[12,7] error: cannot access Filter [ERROR] -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project spring-security-helloworld-annotations: Compilation failure at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)… Read more »
molly
Guest
molly

Hi,

I download this project. When I attempted to access admin page and login as admin. It redirects to home page not admin page. How to solve it?

vijaya
Guest
vijaya

use@RequestMapping(value = “/admin”, method = RequestMethod.GET) instead of @RequestMapping(value = “/admin**”, method = RequestMethod.GET) while debugging i got to know that url mapping is diiferent. but after that getting jasper exception even though we are passing jstl 1.2 jar, if you have any idea on this help me on this

Pascal Baumans
Guest
Pascal Baumans

It’s a pitty to wrote such a promessing sample that finally does not work out of the box.

Vishnudev K
Guest
Vishnudev K

There is no web.xml in the project( still its working.) How it is possible?

Me
Guest
Me

Since we are using WebApplicationInitializer, the web.xml file is NOT required.

Kirill Turutin
Guest
Kirill Turutin

It would be just awesome if you provide an example with custom Login page!
Thank you!

mohan
Guest
mohan
0 down vote favorite I want to create one functionality by implementing spring security. In this I have one login page which contains username and password. After user enter credentials user need to navigate to “Terms and conditions” page. There will be two buttons. Accept and deny. If he accept he can further go inside the application. If he clicks on Deny he will be again come back to login page. After user enter credentials user need to navigate to “Terms and conditions” page. Here user should authenticated against ldap but session should not get start. If user clicks on… Read more »
mohan
Guest
mohan

I want to create one functionality by implementing spring security.
In this I have one login page which contains username and password.
After user enter credentials user need to navigate to “Terms and
conditions” page. There will be two buttons. Accept and deny. If he
accept he can further go inside the application. If he clicks on Deny
he will be again come back to login page.

After user enter credentials user need to navigate to “Terms and
conditions” page. Here user should authenticated against ldap but
session should not get start. If user clicks on “Accept” button of
“Terms and conditions” page then only session should start.

fredy hernan sanchez montaña
Guest
fredy hernan sanchez montaña

I just add the anotations and remove the xml and It did not take the *.config classes

mukesh tangri
Guest
mukesh tangri
I am getting “no such method exception” error when I try to start the server. I was able to get everything working with the xml based authentication but when ever I change it to Annotation based. Below is the full error. As defaultwessecurityhandler extends abstractsecurityexpressionhandler I verified the setapplicationcontext method exists in the jar. Any help to resolve the issue will be appreciated org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration’: Injection of autowired dependencies failed; nested exception is java.lang.NoSuchMethodError: org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler.setApplicationContext(Lorg/springframework/context/ApplicationContext;)V at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)… Read more »
zeyi
Guest
zeyi

Excuse me,have you solved this problem?
I have a same one with you

Chris Linder
Guest
Chris Linder

always getting this error WARNING: No mapping found for HTTP request with URI [/SecurityMVC/welcome] in DispatcherServlet with name ‘dispatcher’

user1234
Guest
user1234

great article,a little description of files like WebSecurityConfigurerAdapter or AbstractAnnotationConfigDispatcherServletInitializer would be more of a help to us.

j.j.marvin
Guest
j.j.marvin

Great sample!

It also can be moved to java 1.8 and latest spring:

1.8
4.1.5.RELEASE
4.0.0.RELEASE
1.2
3.0.1

Tried to jdk 1.8 and Tomcat 8.

Andrew
Guest
Andrew

I’ve made all of the suggested changes and I continue to get the following 404 error

HTTP Status 404 – /spring-security-helloworld-annotation/

type Status report

message /spring-security-helloworld-annotation/

description The requested resource is not available.

Apache Tomcat/8.0.15

see more 0 You must sign in to down-vote this post.

Sam French
Guest
Sam French

Your website is the best. Thanks!

? [c0d3r28] ?
Guest
? [c0d3r28] ?

This tutorial is now heavily out-dated

jcano
Guest
jcano

Changes to pom.xml to make it run. Thanks Myyong.

org.apache.maven.plugins

maven-eclipse-plugin

2.9

true

false

2.0

org.apache.maven.plugins

maven-war-plugin

false

Samuel Henrique
Guest
Samuel Henrique

Can I enable both http basic and login form?

reddy
Guest
reddy

Thank YoU mkyong
:)

lehoangdung
Guest
lehoangdung

Thank you very much! Your article helps me a lot.

Ronald
Guest
Ronald

Hi, If I go to the /admin1 it shows me the admin page, without the login, and the logout.
Should this not either ask me to login or deny me access?

Edgar de Graaff
Guest
Edgar de Graaff

Thanks, this really helped me getting started!

Radha
Guest
Radha
Hi, your blog is succinct. I enjoy reading your blog. Today i tried spring security using annotations and java config. I am getting the following exception: INFO: Initializing Spring root WebApplicationContext INFO : org.springframework.web.context.ContextLoader – Root WebApplicationContext: initialization started INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext – Refreshing Root WebApplicationContext: startup date [Mon Jun 09 07:35:01 IST 2014]; root of context hierarchy INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext – Registering annotated classes: [class com.spring.radha.AppConfig] ERROR: org.springframework.web.context.ContextLoader – Context initialization failed java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:673) at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:480) at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:306) at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:241) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:88) at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70) at java.lang.Class.initAnnotationsIfNecessary(Class.java:3168) at java.lang.Class.getAnnotations(Class.java:3148) at org.springframework.core.type.StandardAnnotationMetadata.isAnnotated(StandardAnnotationMetadata.java:123) at org.springframework.context.annotation.AnnotatedBeanDefinitionReader.registerBean(AnnotatedBeanDefinitionReader.java:138) at org.springframework.context.annotation.AnnotatedBeanDefinitionReader.registerBean(AnnotatedBeanDefinitionReader.java:128) at org.springframework.context.annotation.AnnotatedBeanDefinitionReader.register(AnnotatedBeanDefinitionReader.java:123) at… Read more »
HARSH SHAH
Guest
HARSH SHAH

Solution of your problem .

dispatcher
org.springframework.web.servlet.DispatcherServlet

contextClass

org.springframework.web.context.support.AnnotationConfigWebApplicationContext

contextConfigLocation
com.acme.web.MvcConfig

jef
Guest
jef

Would really appreciate it if you also do a tutorial with jsf integration. Thanks!!

Zach
Guest
Zach

I love your tutorials by the way!

Is there a way to wire security using annotations like this in a preauthentication scenario or does preauthentication r still require xml configuration?

anonymous
Guest
anonymous

In the given Maven dependencies I am not able to find this class:
“AbstractAnnotationConfigDispatcherServletInitializer”

Please let me know if there is any workaround.

ksath
Guest
ksath

Really good example. It seems to me that java config is way more elegant and easy to read than XML based.

Andrew
Guest
Andrew

I’ve made all of the suggested changes and I continue to get the following 404 error

HTTP Status 404 – /spring-security-helloworld-annotation/

type Status report

message /spring-security-helloworld-annotation/

description The requested resource is not available.

Apache Tomcat/8.0.15

Dimi
Guest
Dimi

I can make it run barely with the URL of http://localhost:8080/SpringSecurityHelloWorld/login under Tomcat 7.0.22, but could not get it under jetty.