'Using @RolesAllowed in Spring Boot Application secured with keycloak
I want to create a microservice using Spring Boot 2 and secure it with keycloak. I used the new keycloak-spring-boot-2-starter:4.0.0.Beta3 dependency.
My KeycloakConfig:
@KeycloakConfiguration
@EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = true)
public class KeycloakConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keyCloakAuthProvider = keycloakAuthenticationProvider();
keyCloakAuthProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keyCloakAuthProvider);
}
@Bean
public KeycloakConfigResolver KeyCloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
@Bean
public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(KeycloakAuthenticationProcessingFilter filter) {
//noinspection unchecked
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
@Bean
public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(KeycloakPreAuthActionsFilter filter) {
//noinspection unchecked
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
.and()
.authorizeRequests()
.anyRequest().denyAll();
}
If i replaced my configure-method with following all works fine for my bearer-only-client:
super.configure(http);
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
.and()
.authorizeRequests().antMatchers("/service/example/ping*").hasRole("user")
.anyRequest().denyAll();
But what i want to do is to annotate my Webservices with @RolesAllowed("myRole") to controll access. All other services should be denied by default. If im trying to do, its not working. Does anyone has an idea why and how i could do so?
Greetings from Germany!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
