【问题标题】:Spring security has SimpleGrantedAuthority but hasRole isn't workingSpring 安全性具有 SimpleGrantedAuthority 但 hasRole 不起作用
【发布时间】:2018-11-08 18:25:55
【问题描述】:

我有以下代码...

 private static Collection<? extends GrantedAuthority> 
 readAuthorities(DecodedJWT jwt) {
    ...
    return authorities;
 }

它显示了一个Admin 角色。但是,当我尝试通过...访问网站时...

protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.antMatchers(ADMIN).hasRole(Role.ADMIN.getRoleName())
    ....
}
// Role.ADMIN.getRoleName() == "Admin"

但是当我访问需要管理员权限的站点时,我得到了 403。

我错过了什么?

【问题讨论】:

  • 您的安全类需要扩展“WebSecurityConfigurerAdapter”,还需要使用“@Configuration”和“@EnableWebSecurity”对其进行注释。它可能正在这样做,但我无法用你的样本来判断。当您删除 antMatchers 角色时,它会起作用吗?
  • 已经有注释了
  • 是的,如果我删除该行并仅依赖身份验证,它确实有效

标签: spring-security


【解决方案1】:

事实证明,spring security 会自动将“ROLE_”添加到 .hasRole() 和 @Secured 等角色安全要求的前面。因此,当您将角色分配给用户时,您必须在角色前面加上“ROLE_”。如果这令人困惑,请告诉我,我将通过我的项目中的示例进行更深入的介绍,我在过去 12 小时内一直在研究这个项目,现在没有时间。

【讨论】:

  • 如果你想直接通过授予权限而不是角色来检查,可以使用hasAuthority方法。
猜你喜欢
  • 1970-01-01
  • 2015-06-06
  • 2015-08-27
  • 2017-06-16
  • 2015-06-20
  • 2011-07-03
  • 1970-01-01
相关资源
最近更新 更多