某些背景:我们有一个集成测试类,该类用于测试与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
}
}
前面提到的常量的用法如下:
@PreAuthorize(PREDEFINED_AUTHORIZATION_RULE)
其中常量可能是更复杂的检查,例如:
public static final String PREDEFINED_AUTHORIZATION_RULE =
"hasRole('ADMIN') OR (hasRole('MAINTAINER') AND hasRole('#id'))"
我们已将WebSecurityConfiguration
配置为建议的here,因此添加如下所示的bean:
@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
}
一切工作都像个魅力,除了帖子顶部所示的测试失败,因为在测试环境中,Spring安全性仍然为每个模拟用户角色添加前缀 ROLE _ 。
有人可以阐明如何配置测试类吗?例如-应该如何操作SecurityContext
以在测试中摆脱该前缀?
答案 0 :(得分:1)
这很简单,打开此注释的javadoc并使用authorities
代替roles
答案 1 :(得分:0)
这对我来说很好:
配置:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration {
private final ApplicationContext context;
@Autowired
public GlobalMethodSecurityConfig(ApplicationContext context) {
this.context = context;
}
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler handler =
new DefaultMethodSecurityExpressionHandler();
handler.setDefaultRolePrefix("");
handler.setApplicationContext(context);
return handler;
}
}
测试:
@Test
@WithMockUser(roles = "USER")
void getCard() {
...
}
如果这没有帮助,您可以在GitHub上显示一个有效的代码示例吗? (这可能有助于发现问题)