【问题标题】:When should I prefix ROLE_ with Spring Security?我什么时候应该在 ROLE_ 前面加上 Spring Security?
【发布时间】:2017-06-28 00:26:09
【问题描述】:

在 Spring Security 中,什么时候添加 "ROLE_" 前缀比较合适?在使用@PreAuthorize("hasRole('ROLE_USER')") 的示例中,确实如此。但在这个例子中,它没有:

http
    .httpBasic()
    .and()
    .authorizeRequests()
    .antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")

接下来呢?

SecurityContext securityContext = new SecurityContextImpl();
final Properties users = new Properties();
users.put("joe","secret,ADMIN,enabled");            <-- here
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(users);

Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));         <-- here
AnonymousAuthenticationToken anonymousAuthenticationToken = new AnonymousAuthenticationToken("test", manager.loadUserByUsername("joe"), grantedAuthorities);
        securityContext.setAuthentication(anonymousAuthenticationToken);
        SecurityContextHolder.setContext(securityContext);

有没有具体的使用规则?

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    自动 ROLE_ 前缀

    正如Spring Security 3.x to 4.x migration guide 所说:

    Spring Security 4 自动为 任何角色 加上 ROLE_ 前缀。这 作为SEC-2758的一部分进行了更改

    话虽如此,以下注释中的ROLE_ 前缀是多余的:

    @PreAuthorize("hasRole('ROLE_USER')")
    

    由于您正在调用hasRole 方法,因此暗示您正在传递一个角色。以下表达式也是如此:

    antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
    

    但是对于:

    new SimpleGrantedAuthority("ROLE_ADMIN")
    

    由于这是一个权限,而不是一个角色,您应该添加ROLE_ 前缀(如果您的意图是创建一个角色!)。调用 public InMemoryUserDetailsManager(Properties users) 构造函数也是如此,因为它使用的是权限 internally

    【讨论】:

    • 感谢您的信息。这澄清了我对角色前缀用法的困惑,
    • 一个后续问题,如果将最后两部分代码放在一起,角色数据对用户属性没有任何影响,对吧? grantAuthorities 覆盖用户中的任何角色设置。
    • 老实说我没有完全理解你的问题!
    • 在 users.put("joe","secret,ADMIN,enabled");* 中设置了一个用户角色;* 并且后期 grantAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));和新的 AnonymousAuthenticationToken("test", manager.loadUserByUsername("joe"), grantAuthorities);我的问题是,在这种情况下,说我可以将任何角色放在*线上是否正确。
    • 我不知道,tbh。
    猜你喜欢
    • 2014-12-20
    • 2012-01-09
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2015-07-20
    • 2010-12-30
    相关资源
    最近更新 更多