Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove "ROLE_" prefix when testing Spring security with JUnit?

Some background: we have an integration test class that is used to test constant SPEL strings used with Spring authorization. Simple example:

@SpringBootTest
@RunWith(SpringRunner.class)
public class HasRoleConstantsTest {
    @Test
    @WithMockUser(username = "uname", roles = "ADMIN")
    public void test() {
        // just calling some test method with appropriate annotation
    }
}

Beforementioned constants are used like:

@PreAuthorize(PREDEFINED_AUTHORIZATION_RULE)

where constant could be some bit more complex checks like:

public static final String PREDEFINED_AUTHORIZATION_RULE =
    "hasRole('ADMIN') OR (hasRole('MAINTAINER') AND hasRole('#id'))"

We have configured our WebSecurityConfiguration as suggested here so adding bean like:

@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
    return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
}

Everything works like a charm except that test like shown at the top of the post fails because in test environment Spring security still adds prefix ROLE_ to each mock users role.

Could someone shed some light on how test class should be configured or - for example - how the SecurityContext should be manipulated to get rid of this prefix also on test?

like image 447
pirho Avatar asked Sep 03 '25 03:09

pirho


1 Answers

It is very simple, open javadoc of this annotation and use authorities instead of roles

like image 156
Дима Годиков Avatar answered Sep 06 '25 04:09

Дима Годиков