Spring Security无法与“hasRole('ROLE_ADMIN')”或ROLE_ADMIN一起使用。

4

我正在使用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

我可能错过了什么?


当用户创建账户时,角色将被分配给用户。上述用户被分配为“ROLE_ADMIN”,而其他用户被分配为“ROLE_USER”。该角色保存在数据库的权限表中。 - Frank Atore
1个回答

9

我有一个简短的解释。

您已经通过身份验证成为普通用户,但未被授权查看管理员页面。

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接