Spring Security Hello World Annotation Example
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 :
- Spring 3.2.8.RELEASE
- Spring Security 3.2.3.RELEASE
- Eclipse 4.2
- JDK 1.6
- Maven 3
- Tomcat 7 (Servlet 3.x)
Few Notes
- 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. - Since we are using
WebApplicationInitializer
, theweb.xml
file is NOT required. - 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.
3. Spring Security Dependencies
To use Spring security, you need spring-security-web
and spring-security-config
.
<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 :
- If URL =
/welcome
or/
, return hello page. - If URL =
/admin
, return admin page. - If URL =
/dba
, return admin page.
Later, we will secure the /admin
and /dba
URLs.
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.
<%@page session="false"%>
<html>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1>
</body>
</html>
<%@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
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.
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
.
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.
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.
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
7.2 Try to access /admin
page, Spring Security will intercept the request and redirect to /login
, and a default login form is displayed.
7.3. If username and password is incorrect, error messages will be displayed, and Spring will redirect to this URL /login?error
.
7.4. If username and password is correct, Spring will redirect the request to the original requested URL and display the page.
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.
help WARNING: No mapping found for HTTP request with URI [/SecurityMVC/welcome] in DispatcherServlet with name ‘dispatcher’
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.
thanks really helped
it worked for me too thanks
why there is no web.xml? When i tried it with web.xml its not working. 🙁
I am getting the following error while executing this porgram:
“getServletConfigClasses() did not return any configuration classes”
Can somebody help me understand this?
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.
it is not supported in tomcat 8 and later versions …….try with tomcat 7
Here works fine, when I put in “deployment assembly” the maven dependencies. 😉 tks mkyong
i am a newbie
getting same error
can you please help me out how do you solve this issue
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?
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
It’s a pitty to wrote such a promessing sample that finally does not work out of the box.
It would be just awesome if you provide an example with custom Login page!
Thank you!
I have the same problem. Did not compile
Omg, thank you!
I have created the same structure as you did and now my springSecurity started to work!
I spened 2 days… =)
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
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?
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
There is no web.xml in the project( still its working.) How it is possible?
Since we are using WebApplicationInitializer, the web.xml file is NOT required.
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*/
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 just add the anotations and remove the xml and It did not take the *.config classes
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
Excuse me,have you solved this problem?
I have a same one with you
always getting this error WARNING: No mapping found for HTTP request with URI [/SecurityMVC/welcome] in DispatcherServlet with name ‘dispatcher’
great article,a little description of files like WebSecurityConfigurerAdapter or AbstractAnnotationConfigDispatcherServletInitializer would be more of a help to us.
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.
Your website is the best. Thanks!
This tutorial is now heavily out-dated
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
Can I enable both http basic and login form?
Thank YoU mkyong
🙂
Thank you very much! Your article helps me a lot.
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?
Thanks, this really helped me getting started!
Would really appreciate it if you also do a tutorial with jsf integration. Thanks!!
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?