我正在使用keycloak来验证我的spring Boot 应用程序,如下所示:
@Configuration
public class CustomKeycloakSpringBootConfigResolver extends KeycloakSpringBootConfigResolver {
private final KeycloakDeployment keycloakDeployment;
CustomKeycloakSpringBootConfigResolver(KeycloakSpringBootProperties properties) {
keycloakDeployment = KeycloakDeploymentBuilder.build(properties);
}
@Override
public KeycloakDeployment resolve(HttpFacade.Request facade) {
return keycloakDeployment;
}
@KeycloakConfiguration
class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Override
@Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/account/**").hasRole("user")
.anyRequest().permitAll().and()
.csrf().disable();
}
@Bean
@Override
@ConditionalOnMissingBean(HttpSessionManager.class)
protected HttpSessionManager httpSessionManager() {
return new HttpSessionManager();
}
}
我只需要使用mockmvc编写集成测试,它将测试无论何时访问安全资源,都将触发对keycloak的身份验证,并且在成功的身份验证之后返回资源。
有谁能建议如何实现这一点。
1条答案
按热度按时间2fjabf4q1#
正如在this answer中已经提到的,我在
SecurityContext
中使用KeycloakAuthenticationToken
编写了a lib to ease unit tests。您可以从这里浏览一些包含公寓测试的范例应用程序:https://github.com/ch4mpy/spring-addons/tree/master/samples。
请注意,所有示例都是针对Keycloak服务器运行的,使用KeycloakSpring启动适配器库可能不是最佳选择:
KeycloakMessageServiceTest
:控制器测试如下所示: