【问题标题】:Spring Security does not work with "hasRole('ROLE_ADMIN')" or ROLE_ADMINSpring Security 不适用于“hasRole('ROLE_ADMIN')”或 ROLE_ADMIN
【发布时间】:2017-01-14 06:55:55
【问题描述】:

我使用的是 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' 。该角色保存在数据库的权限表中。

标签: java spring spring-security


【解决方案1】:

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

如果您使用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

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 2011-07-10
    • 2020-06-12
    • 2020-06-15
    • 2017-08-23
    • 2016-08-25
    • 2015-01-12
    • 2017-02-04
    相关资源
    最近更新 更多