Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I prefix ROLE_ with Spring Security?

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?

like image 516
vic Avatar asked Feb 05 '23 03:02

vic


1 Answers

Automatic ROLE_ prefixing

As 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.

like image 174
Ali Dehghani Avatar answered Feb 07 '23 19:02

Ali Dehghani