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?
Automatic
ROLE_
prefixingAs Spring Security 3.x to 4.x migration guide states:
With that being said, the
ROLE_
prefix in the following annotation is redundant:Since you're calling
hasRole
method, the fact that you're passing a role is implied. Same is true for the following expression:But for the:
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 callingpublic InMemoryUserDetailsManager(Properties users)
constructor, since it's using an authority internally.