webweb.config securityyconfigureradapter是什么类

security(26)
保存请求与移除请求
org.springframework.security.web.access.ExceptionTranslationFilter#doFilter{
handleSpringSecurityException(request, response, chain, ase);
org.springframework.security.web.access.ExceptionTranslationFilter#handleSpringSecurityException{
sendStartAuthentication(request,response,chain,new InsufficientAuthenticationException("Full authentication is required to access this resource"));
org.springframework.security.web.access.ExceptionTranslationFilter#sendStartAuthentication{
requestCache.saveRequest(request, response);
org.springframework.security.web.savedrequest.HttpSessionRequestCache#saveRequest{
request.getSession().setAttribute(SAVED_REQUEST, savedRequest);
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#doFilter{
successfulAuthentication(request, response, chain, authResult);
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter#successfulAuthentication{
successHandler.onAuthenticationSuccess(request, response, authResult);
org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess{
requestCache.removeRequest(request, response);
org.springframework.security.web.savedrequest.HttpSessionRequestCache#removeRequest{
session.removeAttribute(SAVED_REQUEST);
org.springframework.security.web.savedrequest.RequestCacheAwareFilter#doFilter{
HttpServletRequest wrappedSavedRequest = requestCache.getMatchingRequest((HttpServletRequest) request, (HttpServletResponse) response);
org.springframework.security.web.savedrequest.HttpSessionRequestCache#getMatchingRequest{
removeRequest(request, response);
org.springframework.security.web.savedrequest.HttpSessionRequestCache#removeRequest{
session.removeAttribute(SAVED_REQUEST);
保存Session(如果要持久化到redis就要看
org.springframework.security.web.context.SecurityContextPersistenceFilter#doFilter{
repo.saveContext(contextAfterChainExecution, holder.getRequest(),holder.getResponse());
org.springframework.security.web.context.HttpSessionSecurityContextRepository#saveContext{
responseWrapper.saveContext(context);
org.springframework.security.web.context.HttpSessionSecurityContextRepository.SaveToSessionResponseWrapper#saveContext{
HttpSession httpSession = request.getSession(false);
httpSession.setAttribute(springSecurityContextKey, context);
这个repo在springSecurity有两种实现:org.springframework.security.web.context.HttpSessionSecurityContextRepository和org.springframework.security.web.context.NullSecurityContextRepository(这种实现为了不保存session,比如服务端保持无状态),如果想要注入自己的实现,比如保存到数据库之类的方法如下:重写org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
http.securityContext().securityContextRepository(securityContextRepository)
授权拦截处理:
.authorizeRequests().antMatchers("/me").access("#oauth2.hasScope('read')")这一类:
org.springframework.security.web.access.intercept.FilterSecurityInterceptor#invoke{
InterceptorStatusToken token = super.beforeInvocation(fi);
org.springframework.security.access.intercept.AbstractSecurityInterceptor#beforeInvocation{
this.accessDecisionManager.decide(authenticated, object, attributes);
启用全局方法安全这一类(详细看&十springSecurity启用全局方法使用aop的分析&):对拦截方法类生成代理,在调用方法前先调用前置通知
org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor#invoke{
InterceptorStatusToken token = super.beforeInvocation(mi);
org.springframework.security.access.intercept.AbstractSecurityInterceptor#beforeInvocation{
this.accessDecisionManager.decide(authenticated, object, attributes);
这两类最终都由decide方法作出决定是否授权
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:448415次
积分:5958
积分:5958
排名:第2722名
原创:156篇
转载:51篇
评论:100条
(4)(4)(15)(5)(4)(7)(8)(4)(3)(1)(3)(5)(10)(10)(9)(14)(2)(12)(11)(5)(8)(8)(9)(12)(1)(3)(14)(1)(4)(11)Spring Security Java Config - Stack Overflow
to customize your list.
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
J it only takes a minute:
Join the Stack Overflow community to:
Ask programming questions
Answer and help your peers
Get recognized for your expertise
I'm trying to use JavaConfig instead of XML configuration for Spring Security.
I would like to use @PreAuthorization for declaring access rights.
My Spring Security Config looks like this:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity( prePostEnabled = true )
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void registerAuthentication( AuthenticationManagerBuilder auth ) throws Exception {
.inMemoryAuthentication()
.withUser( "user" ).password( "password" ).roles( "USER" );
However, this doesn't work. Once I deploy my web application I receive an error Error creating bean with name 'methodSecurityInterceptor' defined in class path resource.
After some research I found out that I have to add the aopalliance library to my project. Unfortunately that didn't resolved my problem.
Here is the complete stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Instanti nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.aopalliance.intercept.MethodInterceptor org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityInterceptor() throws java.lang.Exception] nested exception is java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:592)
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:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
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:381)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
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.manageApp(HostConfig.java:1558)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:620)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:567)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1487)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:97)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1328)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1420)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:848)
at sun.reflect.GeneratedMethodAccessor42.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
at sun.rmi.transport.Transport$1.run(Transport.java:177)
at sun.rmi.transport.Transport$1.run(Transport.java:174)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:556)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:811)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:670)
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:744)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.aopalliance.intercept.MethodInterceptor org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityInterceptor() throws java.lang.Exception] nested exception is java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581)
... 56 more
Caused by: java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
at org.springframework.util.Assert.isTrue(Assert.java:65)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.lazyBean(GlobalMethodSecurityConfiguration.java:352)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.authenticationManager(GlobalMethodSecurityConfiguration.java:240)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityInterceptor(GlobalMethodSecurityConfiguration.java:116)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerByCGLIB$$890899ea.CGLIB$methodSecurityInterceptor$2(&generated&)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerByCGLIB$$890899ea$$FastClassByCGLIB$$fba343c4.invoke(&generated&)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:326)
at org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration$$EnhancerByCGLIB$$890899ea.methodSecurityInterceptor(&generated&)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
... 57 more
14.9k65979
According to your stacktrace, there’s no AuthenticationManager bean in your context.
Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
It seems that you need to explicitly expose AuthenticationManager try this:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser( "user" ).password( "password" ).roles( "USER" );
@Bean @Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
2,77511725
from the stacktrace, you don't have authentication manager defiend correctly :
Caused by: java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
Here is working example :
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
Just add the global method annotation, and change to method to not override and be autowired.
26.5k30119208
As NimChimpsky notes, Spring 3.2.0.RELEASE requires a configuration update.
Using this configuration, I was getting exactly the same exception as the OP, but only about half the time. The other half of the time the app started up just fine. I assume that there's some kind of race condition.
Originally I was pulling the security configuration in using @Import on my root configuration:
@Configuration
@Import(SecurityConfig.class)
... other annotations ...
public class RootConfig {
When I replaced that with
public class WebAppInit extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class&?&[] getRootConfigClasses() {
return new Class&?&[] { RootConfig.class, SecurityConfig.class };
the problem went away. Didn't dive into the reasons why, so I can't speak to that, but you might give it a try.
14.9k65979
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
The week's top questions and answers
Important community announcements
Questions that need answers
By subscribing, you agree to the
Stack Overflow works best with JavaScript enabledSpring Security 4 基于角色的登录例子(带源码)
本教程将向你展示Spring Security 中基于 角色的登录。也就是说,根据其角色登录以后重定向到不同的url。
一般来说,我们需要自定义一个Success-Handler 来根据用户角色处理登录用户的重定向到对应的url。
这个功能在Spring Security 里面已经提供了。
SimpleUrlAuthenticationSuccessHandler 含有常用的successhandler的常用逻辑。
我们仅需要拓展它,实现我们自己的逻辑即可。
一旦我们获得了successhandler(处理器),我们将通过formLogin()或loginPage()来注册它,
完整的例子如下:
--------------------------------------------------------
下面是用的技术
Dear ${user}, Welcome to Home Page.
Spring 4.1.6.RELEASE
Spring Security 4.0.1.RELEASE
Tomcat 8.0.21
Eclipse JUNO Service Release 2
让我们开始吧
第1步: 项目文件目录结构
下面是最终的项目目录结构
现在让我为你展示上面目录结构里面的内容和每个的详细介绍。
第2步: 更新 pom.xml 包含所需的依赖
com.websystique.springsecurity
SpringSecurityRoleBasedLoginExample
SpringSecurityRoleBasedLoginExample
4.1.6.RELEASE
4.0.1.RELEASE
org.springframework
spring-core
${springframework.version}
org.springframework
spring-web
${springframework.version}
org.springframework
spring-webmvc
${springframework.version}
org.springframework.security
spring-security-web
${springsecurity.version}
org.springframework.security
spring-security-config
${springsecurity.version}
javax.servlet
javax.servlet-api
javax.servlet.jsp
javax.servlet.jsp-api
javax.servlet
org.apache.maven.plugins
maven-compiler-plugin
org.apache.maven.plugins
maven-war-plugin
src/main/webapp
SpringSecurityRoleBasedLoginExample
SpringSecurityRoleBasedLoginExample
第3步: 添加 Spring Security 配置类
添加spring security到我们应用中第一步是要创建Spring Security
这个配置创建一个叫springSecurityFilterChain的Servlet过滤器,来对我们应用中所有的安全相关的事项(保护应用的所有url,验证用户名密码,表单重定向等)负责。
package com.websystique.springsecurity.
import org.springframework.beans.factory.annotation.A
import org.springframework.context.annotation.C
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerB
import org.springframework.security.config.annotation.web.builders.HttpS
import org.springframework.security.config.annotation.web.configuration.EnableWebS
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerA
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
CustomSuccessHandler customSuccessH
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser(&bill&).password(&abc123&).roles(&USER&);
auth.inMemoryAuthentication().withUser(&admin&).password(&root123&).roles(&ADMIN&);
auth.inMemoryAuthentication().withUser(&dba&).password(&root123&).roles(&ADMIN&,&DBA&);
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(&/&, &/home&).access(&hasRole('USER')&)
.antMatchers(&/admin/**&).access(&hasRole('ADMIN')&)
.antMatchers(&/db/**&).access(&hasRole('ADMIN') and hasRole('DBA')&)
.and().formLogin().loginPage(&/login&).successHandler(customSuccessHandler)
.usernameParameter(&ssoId&).passwordParameter(&password&)
.and().csrf()
.and().exceptionHandling().accessDeniedPage(&/Access_Denied&);
此类和前几篇文章类似,只是下面这点有区别:formLogin().loginPage(&/login&).successHandler(customSuccessHandler)
重点是successHandler,这个类定义了处理successHandler的逻辑。在本例中根据 角色USER/ADMIN/DBA重定向到home/admin/db
以上配置 对应的xml配置文件:
下面是 上面的类里面涉及的Success-Handler
package com.websystique.springsecurity.
import java.io.IOE
import java.util.ArrayL
import java.util.C
import java.util.L
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.springframework.security.core.A
import org.springframework.security.core.GrantedA
import org.springframework.security.web.DefaultRedirectS
import org.springframework.security.web.RedirectS
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessH
import org.
@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println(&Can't redirect&);
redirectStrategy.sendRedirect(request, response, targetUrl);
* This method extracts the roles of currently logged-in user and returns
* appropriate URL according to his/her role.
protected String determineTargetUrl(Authentication authentication) {
String url = &&;
Collection authorities = authentication.getAuthorities();
List roles = new ArrayList();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
if (isDba(roles)) {
url = &/db&;
} else if (isAdmin(roles)) {
url = &/admin&;
} else if (isUser(roles)) {
url = &/home&;
url = &/accessDenied&;
private boolean isUser(List roles) {
if (roles.contains(&ROLE_USER&)) {
private boolean isAdmin(List roles) {
if (roles.contains(&ROLE_ADMIN&)) {
private boolean isDba(List roles) {
if (roles.contains(&ROLE_DBA&)) {
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectS
protected RedirectStrategy getRedirectStrategy() {
return redirectS
注意:我们是怎样拓展SimpleUrlAuthenticationSuccessHandler类的,重写了handle()方法,
简单的调用重定向使用配置的RedirectStrategy,其中通过determineTargetUrl方法返回对应的url。
此方法从Authentication 对象中提取角色然后根据 角色构建 对应的url.最后在Spring Security 负责所有重定向事务的RedirectStrategy (重定向策略)来重定向请求到指定的url
其余部分和以前的文章是一样的。
第4步: 注册springSecurityFilter
下面是定制初始化war包中的springSecurityFilter(第三步中的)注册类
package com.websystique.springsecurity.
import org.springframework.security.web.context.AbstractSecurityWebApplicationI
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
上面配置对应的xml配置如下:
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
第5步: 添加 Controller(控制器)
package com.websystique.springsecurity.
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.springframework.security.core.A
import org.springframework.security.core.context.SecurityContextH
import org.springframework.security.core.userdetails.UserD
import org.springframework.security.web.authentication.logout.SecurityContextLogoutH
import org.springframework.stereotype.C
import org.springframework.ui.ModelM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
@Controller
public class HelloWorldController {
@RequestMapping(value = { &/&, &/home& }, method = RequestMethod.GET)
public String homePage(ModelMap model) {
model.addAttribute(&user&, getPrincipal());
return &welcome&;
@RequestMapping(value = &/admin&, method = RequestMethod.GET)
public String adminPage(ModelMap model) {
model.addAttribute(&user&, getPrincipal());
return &admin&;
@RequestMapping(value = &/db&, method = RequestMethod.GET)
public String dbaPage(ModelMap model) {
model.addAttribute(&user&, getPrincipal());
return &dba&;
@RequestMapping(value = &/Access_Denied&, method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
model.addAttribute(&user&, getPrincipal());
return &accessDenied&;
@RequestMapping(value = &/login&, method = RequestMethod.GET)
public String loginPage() {
return &login&;
@RequestMapping(value=&/logout&, method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
return &redirect:/login?logout&;
private String getPrincipal(){
String userName =
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
userName = ((UserDetails)principal).getUsername();
userName = principal.toString();
return userN
第6步: 添加 SpringMVC 配置类
package com.websystique.springsecurity.
import org.springframework.context.annotation.B
import org.springframework.ponentS
import org.springframework.context.annotation.C
import org.springframework.web.servlet.ViewR
import org.springframework.web.servlet.config.annotation.EnableWebM
import org.springframework.web.servlet.view.InternalResourceViewR
import org.springframework.web.servlet.config.annotation.ResourceHandlerR
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerA
import org.springframework.web.servlet.view.JstlV
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = &com.websystique.springsecurity&)
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter{
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix(&/WEB-INF/views/&);
viewResolver.setSuffix(&.jsp&);
return viewR
* Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(&/static/**&).addResourceLocations(&/static/&);
---------译者增加 start---明明如月--------
以上配置对应的xml配置如下:
---------译者增加end---明明如月--------
第7: 添加Initializer(初始化器)类
package com.websystique.springsecurity.
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletI
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class[] getRootConfigClasses() {
return new Class[] { HelloWorldConfiguration.class };
protected Class[] getServletConfigClasses() {
protected String[] getServletMappings() {
return new String[] { &/& };
第8步: 添加视图
此视图为登录面板增加了css
&%@ page language=&java& contentType=&text/ charset=ISO-8859-1& pageEncoding=&ISO-8859-1&%&
&%@ taglib prefix=&c& uri=&/jsp/jstl/core&%&
注意:和CSRF 相关的是
这一行的目的是防止CSRF攻击。正如你所见jsp中CSRF参数使用EL表达式获取的。因此需要允许el表达式:
需要在jsp头添加如下一行:
&%@ page isELIgnored=&false&%&
welcome.jsp
&%@ page language=&java& contentType=&text/ charset=ISO-8859-1& pageEncoding=&ISO-8859-1&%&
&%@ taglib prefix=&c& uri=&/jsp/jstl/core&%&
&%@ page language=&java& contentType=&text/ charset=ISO-8859-1& pageEncoding=&ISO-8859-1&%&
&%@ taglib prefix=&c& uri=&/jsp/jstl/core&%&
&%@ page language=&java& contentType=&text/ charset=ISO-8859-1& pageEncoding=&ISO-8859-1&%&
&%@ taglib prefix=&c& uri=&/jsp/jstl/core&%&
accessDenied.jsp
&%@ page language=&java& contentType=&text/ charset=ISO-8859-1& pageEncoding=&ISO-8859-1&%&
&%@ taglib prefix=&c& uri=&/jsp/jstl/core&%&
例子中所需的css文件
background-color:#2F2F2F;
body, #mainWrapper {
height: 100%;
background-image: -webkit-gradient(
right bottom,
right top,
color-stop(0, #EDEDED),
color-stop(0.08, #EAEAEA),
color-stop(1, #2F2F2F),
color-stop(1, #AAAAAA)
background-image: -o-linear-gradient(top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
background-image: -moz-linear-gradient(top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
background-image: -webkit-linear-gradient(top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
background-image: -ms-linear-gradient(top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
background-image: linear-gradient(to top, #EDEDED 0%, #EAEAEA 8%, #2F2F2F 100%, #AAAAAA 100%);
body, #mainWrapper, .form-control{
font-size:12px!
#mainWrapper {
height: 100
padding-left:10
padding-right:10
padding-bottom:10
#authHeaderWrapper{
width: 100%;
height:3%;
padding-top:5
padding-bottom:5
.login-container {
margin-top: 100
background-color:
width: 40%;
left: 30%;
.login-card {
width: 80%;
.login-form {
padding: 10%;
第9步: 构建和部署应用
现在构建 war 包(通过eclipse或者myeclipse)或者通过maven 命令行(mvn clean install). 在一个Servlet 3.0 容器中发布本应用. 在这里我使用的是tomcat, 我将war 文件放到tomcat webapps 文件夹然后点击tomcat安装目录的bin文件夹下的start.bat.
打开浏览器 在地址栏输入localhost:8080/SpringSecurityRoleBasedLoginExample/并回车
输入DBA角色的账户
提交表单,因为当前登录的用户时DBA角色,登录后将被重定向到/db 页面。
退出后登录USER权限的用户
然后访问admin 页面,将看到 权限拒绝页面
退出后登录ADMIN 角色的账户
本文结束,下一篇文章我们精介绍基于Hibernate注解的数据库的Spring Security 权限验证。
项目地址:/?smd_process_download=1&download_id=1495
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'}

我要回帖

更多关于 websocketconfigurer 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信