In Spring Security, when is it appropriate to add the "ROLE_" prefix?  In examples using @PreAuthorize("hasRole('ROLE_USER')"), it does. But in this example, it doesn't: 
http
    .httpBasic()
    .and()
    .authorizeRequests()
    .antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
What about the following?
SecurityContext securityContext = new SecurityContextImpl();
final Properties users = new Properties();
users.put("joe","secret,ADMIN,enabled");            <-- here
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(users);
and
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);
Are there any specific rules of the usage?
ROLE_ prefixingAs Spring Security 3.x to 4.x migration guide states:
Spring Security 4 automatically prefixes any role with
ROLE_. The changes were made as part of SEC-2758
With that being said, the ROLE_ prefix in the following annotation is redundant:
@PreAuthorize("hasRole('ROLE_USER')")
Since you're calling hasRole method, the fact that you're passing a role is implied. Same is true for the following expression:
antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
But for the:
new SimpleGrantedAuthority("ROLE_ADMIN")
Since this is an authority, not a role, you should add the ROLE_ prefix (If your intent is to create a role!). Same is true for calling public InMemoryUserDetailsManager(Properties users) constructor, since it's using an authority internally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With