我应该在什么时候给ROLE_加上Spring Security前缀?

vic*_*vic 2 java spring spring-security

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

http
    .httpBasic()
    .and()
    .authorizeRequests()
    .antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
Run Code Online (Sandbox Code Playgroud)

接下来呢?

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

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);
Run Code Online (Sandbox Code Playgroud)

是否有使用的特定规则?

Ali*_*ani 5

自动ROLE_前缀

Spring Security 3.x到4.x的迁移指南指出:

Spring Security 4自动为任何角色添加前缀ROLE_。所做的更改是SEC-2758的一部分

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

@PreAuthorize("hasRole('ROLE_USER')")
Run Code Online (Sandbox Code Playgroud)

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

antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
Run Code Online (Sandbox Code Playgroud)

但对于:

new SimpleGrantedAuthority("ROLE_ADMIN")
Run Code Online (Sandbox Code Playgroud)

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