Spring Security不适用于" hasRole(' ROLE_ADMIN')"或者ROLE_ADMIN

时间:2016-06-25 15:28:46

标签: java spring spring-security

我使用的是Spring Security 4.1版。如果我在安全配置中指定access="hasRole('ROLE_ADMIN')"access="ROLE_ADMIN",我就可以登录,但我无法访问我的管理页面。

<security:http use-expressions="true">
    <security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
    <!-- security:intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" / -->
    <security:intercept-url pattern="/createmanufsensors" access="isAuthenticated()" />
</security:http>
<security:global-method-security secured-annotations="enabled"></security:global-method-security>

以下是调试错误:

DEBUG [http-bio-8080-exec-10] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] Secure object: FilterInvocation: URL: /admin; Attributes: [hasRole('ROLE_ADMIN')]     
2016-06-25 10:07:53,667 [] DEBUG [http-bio-8080-exec-10] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@cc305a73: Principal: org.springframework.security.core.userdetails.User@74b46745: Username: francatore                                                  ; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN                                ; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 7F702A6911A71EA5556C750B6D424FF5; Granted Authorities: ROLE_ADMIN                                   
2016-06-25 10:07:53,667 [] DEBUG [http-bio-8080-exec-10] [org.springframework.security.access.vote.AffirmativeBased] Voter: org.springframework.security.web.access.expression.WebExpressionVoter@170ea084, returned: -1
2016-06-25 10:07:53,668 [] DEBUG [http-bio-8080-exec-10] [org.springframework.security.web.access.ExceptionTranslationFilter] Access is denied (user is not anonymous); delegating to AccessDeniedHandler

我可能会错过什么?

1 个答案:

答案 0 :(得分:7)

我对此有一个小解释。 您在这里以普通用户身份进行身份验证,但无权查看管理页面。

如果您使用的是access="hasRole('ROLE_ADMIN')"表达式,那么Spring EL类(即SecurityExpressionRoot)会为每个角色添加前缀 ROLE_ 我们在hasRole()表达式中提供的。因此,在您的情况下,您在hasRole('ROLE_ADMIN')中提供的角色会解析为ROLE_ROLE_ADMIN

这就是为什么您被认证为拥有ROLE_ADMIN的用户。但是要向Spring Security框架查看管理页面,用户必须具有该角色 ROLE_ROLE_ADMIN (因为SecurityExpressionRoot类添加了ROLE_前缀)。

为此,请在代码中删除ROLE_前缀,即此处access="hasRole('ADMIN')" 因此,Spring Security将自动添加ROLE_前缀。 并确保您已将数据库中的管理员角色指定为ROLE_ADMIN