Spring Security出现问题:Access is denied 及我的解决方案

近日使用spring security,xml文件如下:

......

<!-- 页面拦截规则 -->
	<http pattern="/shoplogin.html" security="none"></http>
	<http pattern="/loginerror.html" security="none"></http>
	<http pattern="/css/**" security="none"></http>
	<http pattern="/img/**" security="none"></http>
	<http pattern="/js/**" security="none"></http>
	<http pattern="/plugins/**" security="none"></http>
	
	<http use-expressions="false">
		<intercept-url pattern="/**" access="ROLE_USER" />

		<form-login login-page="/shoplogin.html"
			login-processing-url="/login" 
			default-target-url="/admin/index.html"
			authentication-failure-url="/shoplogin.html"
			always-use-default-target="true" />
		
		......

        <!-- 指定自定义过滤器 -->
        <custom-filter ref="authenticationFilter" before="FORM_LOGIN_FILTER" />
	</http>
	
	<!-- 自定义过滤器 -->
    <beans:bean id="authenticationFilter" class="com.shopping.shop.util.TestLoginFilter">
        <beans:property name="filterProcessesUrl" value="/login" />
        <beans:property name="authenticationManager" ref="authenticationManager" />
    </beans:bean>

	<authentication-manager alias="authenticationManager">
		<authentication-provider user-service-ref="userDetailService">
			<!-- <password-encoder ref="bcryptEncoder"></password-encoder> -->
		</authentication-provider>
	</authentication-manager>

    <beans:bean id="userDetailService" class="com.shopping.shop.util.UserDetailsServiceImpl">
		<beans:property name="sellerService" ref="sellerService"/>
	</beans:bean>

......

自定义类:com.shopping.shop.util.UserDetailsServiceImpl(userDetailService)如下:

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		System.out.println("经过了UserDetailsServiceImpl");
		//构建角色列表
		List<GrantedAuthority> grantAuths=new ArrayList<GrantedAuthority>();
		grantAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));
		//得到商家对象
		List<TbSeller> sellers = sellerService.findList(username);
		if(sellers != null) {
			for(TbSeller seller : sellers) {
				if(seller.getStatus().equals("1")) {
					return new User(username,seller.getPassword(),grantAuths);
				}
			}
		}
		return null;
	}

访问项目出现问题,如下:

......

2019-01-24 17:11:49,691 DEBUG [org.springframework.security.web.access.ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
	at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
	at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:150)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:206)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:206)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:106)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
	at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)

......

处理上述问题:

Access is denied:访问被拒绝

可能的原因:

1. You have logged in with a user that has given a role but accessing a URL pattern which is not authorized to that user.

2.  Or You have logged in with a user and accessing a method which is not authorized to that user role.

 

经过一番查找,终于发现我在xml文件中定义的是 “access="ROLE_USER",在userDetailService中却是:grantAuths.add(new SimpleGrantedAuthority("ROLE_SELLER"));

难怪,改正上述错误,问题OK。

在解决上述问题的过程中,我同样看见许多出现“Access is denied”的例子,但他们的解决方案在我这儿却行不通。最终解决问题之后理解到:Access is denied 只是说明了出现问题的原因,或者说是类型,他只是定义了一个大的解决方向而具体的解决方案还得视具体情况决定。

最后,附上本人学习Security的一份小demo:https://download.csdn.net/download/txd2016_5_11/10943130,程序已经跑通,里边附加了一些本人的理解,希望能对大家产生一点帮助。

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
这个错误通常是由于缺少必要的Spring Security配置导致的。在Spring Boot Actuator中,有一个名为`managementSecurityFilterChain`的过滤器链需要一个类型为`HttpSecurity`的Bean来进行配置。 要解决这个问题,你可以在你的项目中添加一个配置类,用于配置Spring Security的相关设置。以下是一个示例配置类: ```java import org.springframework.context.annotation.Configuration; 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 { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/actuator/**").permitAll() // 允许访问Actuator端点 .anyRequest().authenticated() // 其他请求需要身份认证 .and() .httpBasic(); // 使用HTTP基本认证 } } ``` 在上述配置类中,我们允许所有请求访问Actuator端点`/actuator/**`,并对其他请求进行身份认证。你可以根据你的需求进行修改和扩展。 确保将此配置类放置在能够被Spring Boot扫描到的位置,以确保它能够生效。一旦配置类生效,`managementSecurityFilterChain`将能够找到所需的`HttpSecurity` Bean,并解决该错误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值