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

51 comments on “Spring Security Hello World Annotation Example

  1. Omg, thank you!
    I have created the same structure as you did and now my springSecurity started to work!
    I spened 2 days… =)

  2. hiiii i got error while runing the project

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘springSecurityFilterChain’ defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/web/filter/CorsFilter
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5155)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5680)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1702)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1692)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/web/filter/CorsFilter
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
    … 25 more
    Caused by: java.lang.NoClassDefFoundError: org/springframework/web/filter/CorsFilter
    at org.springframework.security.config.annotation.web.builders.FilterComparator.(FilterComparator.java:74)
    at org.springframework.security.config.annotation.web.builders.HttpSecurity.(HttpSecurity.java:121)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:178)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:290)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:67)
    at com.spring.SecurityConfig$$EnhancerBySpringCGLIB$$10da8f75.init()
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$622fd62d.CGLIB$springSecurityFilterChain$0()
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$622fd62d$$FastClassBySpringCGLIB$$683cc49f.invoke()
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$622fd62d.springSecurityFilterChain()
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
    … 26 more

  3. 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?

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

    Can somebody help me understand this?

  5. 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)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
    Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
    at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:656)
    at org.apache.maven.plugin.CompilerMojo.execute(CompilerMojo.java:128)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    … 20 more

  6. 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?

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

  7. 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 “Accept” button of
    “Terms and conditions” page then only session should start.

    I can not add much code here because it is confidential. However below things are there in configuration.

    /*impactAuthenticationFilter is class which extends AbstractPreAuthenticatedProcessingFilter*/

    /*successHandler is class which extends SavedRequestAwareAuthenticationSuccessHandler*/

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

  9. 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)

    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)

    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)

    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)

    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)

    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992)

    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)

    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)

    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)

    at java.util.concurrent.FutureTask.run(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

    at java.lang.Thread.run(Unknown Source)

    Caused by: java.lang.NoSuchMethodError: org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler.setApplicationContext(Lorg/springframework/context/ApplicationContext;)V

    at org.springframework.security.config.annotation.web.builders.WebSecurity.setApplicationContext(WebSecurity.java:342)

    at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:119)

    at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:94)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1558)

    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:399)

    at org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor.postProcess(AutowireBeanFactoryObjectPostProcessor.java:60)

    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(WebSecurityConfiguration.java:119)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

    at java.lang.reflect.Method.invoke(Unknown Source)

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:642)

    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)

    … 22 more

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

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

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

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

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

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

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

  17. I´ve tried to run this example, and another made by myself but in both I have Error 404. I´m using JDK 1.7 and Tomcat 8. There is any test to do to detect the problem?

      1. Same thing for me, but I find a workaround by implementing WebApplicationInitializer like this

        public class SpringMvcInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer
        implements WebApplicationInitializer

  18. ————————————————————————

    Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project spring-security-helloworld-annotation: Compilation failure: Compilation failure:

    com/mkyong/config/core/SpringMvcInitializer.java:[7,7] error: cannot access ServletException

    com/mkyong/config/SecurityConfig.java:[12,7] error: cannot access Filter

    -> [Help 1]

  19. 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?

  20. 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 org.springframework.web.context.support.AnnotationConfigWebApplicationContext.loadBeanDefinitions(AnnotationConfigWebApplicationContext.java:211)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
    Jun 09, 2014 7:35:01 AM org.apache.catalina.core.StandardContext listenerStart
    SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    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 org.springframework.web.context.support.AnnotationConfigWebApplicationContext.loadBeanDefinitions(AnnotationConfigWebApplicationContext.java:211)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4887)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5381)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

    Jun 09, 2014 7:35:01 AM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Error listenerStart
    Jun 09, 2014 7:35:01 AM org.apache.catalina.core.StandardContext startInternal
    SEVERE: Context [/radha] startup failed due to previous errors
    Jun 09, 2014 7:35:01 AM org.apache.catalina.core.ApplicationContext log
    INFO: Closing Spring root WebApplicationContext
    INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext – Closing Root WebApplicationContext: startup date [Mon Jun 09 07:35:01 IST 2014]; root of context hierarchy
    WARN : org.springframework.web.context.support.AnnotationConfigWebApplicationContext – Exception thrown from ApplicationListener handling ContextClosedEvent
    java.lang.IllegalStateException: ApplicationEventMulticaster not initialized – call ‘refresh’ before multicasting events via the context: Root WebApplicationContext: startup date [Mon Jun 09 07:35:01 IST 2014]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:347)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:334)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1049)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:1010)
    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4927)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5573)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
    WARN : org.springframework.web.context.support.AnnotationConfigWebApplicationContext – Exception thrown from LifecycleProcessor on context close
    java.lang.IllegalStateException: LifecycleProcessor not initialized – call ‘refresh’ before invoking lifecycle methods via the context: Root WebApplicationContext: startup date [Mon Jun 09 07:35:01 IST 2014]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:360)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1057)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:1010)
    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4927)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5573)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)
    Jun 09, 2014 7:35:01 AM org.apache.catalina.core.StandardContext listenerStop
    SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
    java.lang.IllegalStateException: BeanFactory not initialized or already closed – call ‘refresh’ before accessing beans via the ApplicationContext
    at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:171)
    at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1090)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1064)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:1010)
    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4927)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5573)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

    1. Solution of your problem .

      dispatcher
      org.springframework.web.servlet.DispatcherServlet

      contextClass

      org.springframework.web.context.support.AnnotationConfigWebApplicationContext

      contextConfigLocation
      com.acme.web.MvcConfig

  21. 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?

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

    Please let me know if there is any workaround.

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

Leave a Comment

Your email address will not be published. Required fields are marked *