使用 JUnit 测试 Spring 安全性时如何删除“ROLE_”前缀?

pir*_*rho 4 java junit spring spring-security spring-test

一些背景:我们有一个集成测试类,用于测试与 Spring 授权一起使用的常量 SPEL 字符串。简单的例子:

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

前面提到的常量的用法如下:

@PreAuthorize(PREDEFINED_AUTHORIZATION_RULE)
Run Code Online (Sandbox Code Playgroud)

其中常量可能是一些更复杂的检查,例如:

public static final String PREDEFINED_AUTHORIZATION_RULE =
    "hasRole('ADMIN') OR (hasRole('MAINTAINER') AND hasRole('#id'))"
Run Code Online (Sandbox Code Playgroud)

我们已经按照此处WebSecurityConfiguration的建议进行了配置,因此添加了如下 bean:

@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
    return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
}
Run Code Online (Sandbox Code Playgroud)

一切都像魅力一样,除了帖子顶部所示的测试失败,因为在测试环境中 Spring security 仍然向每个模拟用户角色添加前缀ROLE_ 。

有人可以阐明如何配置测试类,或者 - 例如 - 应该如何SecurityContext操作以在测试中删除此前缀?

Дим*_*ков 5

很简单,打开这个注解的javadoc并使用authorities而不是roles