【问题标题】:Spring Security - GrantedAuthority and role-based accessSpring Security - GrantedAuthority 和基于角色的访问
【发布时间】:2019-08-08 05:02:08
【问题描述】:

我正在使用自定义的 UserDetailService,它可以很好地进行身份验证。问题是我不能使用基于角色的约束。

奇怪的是,我从控制器那里得到了正确的权限:

public ModelAndView getMembers(HttpServletRequest request, Authentication auth) 
{
   if(auth != null)
   {
      for (GrantedAuthority ga : auth.getAuthorities())
      {
         // works find and logs "ADMIN", btw. I'm using SimpleGrantedAuthority
         this.logger.debug("0{}", ga);
      }
   }
}

但是有配置

http
   .csrf().disable()
   .authorizeRequests()
   .antMatchers("/Admin/**").hasRole("ADMIN")
   …

用户无法访问页面,例如/管理员/成员。

thymeleaf-security-tags 也是如此,例如

<div sec:authorize="isAuthenticated() && hasRole('ADMIN')">Hello Admin!</div>

不显示“您好管理员!”对于控制器记录权限“ADMIN”的用户。

我猜我遗漏了什么或使用了错误的东西。

感谢您的时间和帮助。

【问题讨论】:

  • 你试过 hasRole('ROLE_ADMIN') 还是使用 hasAuthority('ADMIN')
  • 谢谢,hasRole('ROLE_ADMIN') 不起作用,但 hasAuthority('ADMIN') 方法就像一个魅力......在 thymeleaf-security 和 spring 配置中。有谁知道如何在自定义 UserDetailService 中设置主体角色。
  • 关闭此问题并打开一个新问题

标签: spring security roles authority


【解决方案1】:

正如 cmets 中所说,您必须使用 hasAuthority("ADMIN") 而不是 hasRole("ADMIN")

区分授予权限和角色很重要。 Baeldung 有一篇文章对此进行了解释:Granted Authority Versus Role in Spring Security。从这篇文章我们可以理解其中的区别:

授权

在 Spring Security 中,我们可以将每个 GrantedAuthority 视为一个单独的权限。示例可能包括 READ_AUTHORITY、WRITE_PRIVILEGE 甚至 CAN_EXECUTE_AS_ROOT。 [...]

当直接使用 GrantedAuthority 时,例如通过使用 hasAuthority('READ_AUTHORITY') 之类的表达式,我们以细粒度的方式限制访问。

作为权威的角色

类似地,在 Spring Security 中,我们可以将每个角色视为粗粒度的 GrantedAuthority,它表示为字符串并以“ROLE”为前缀。当直接使用 Role 时,例如通过 hasRole(“ADMIN”) 之类的表达式,我们以粗粒度方式限制访问。

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 2018-11-28
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2016-10-14
    • 2020-12-18
    相关资源
    最近更新 更多