I migrate from Zuul Gateway to Spring Gateway. This forced me to abandon Servlets for Webflux. I use KeyCloak and KeyCloak roles for authentication and authorization.
There is no official reactive KeyCloak implementation, so I use Spring OAuth2 instead. It works fine apart from retrieving the roles.
I cannot use servlet interceptors, because servlets are not allowed by WebFlux. Also, it seems Spring Gateway in general does not allow intercepting response bodies.
Thus my problem remains: How do I retrieve KeyCloak roles in Spring Gateway, so that they can be used by its security?
Here is some sample code I use: In class SecurityConfig.java:
@Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.csrf().disable().authorizeExchange(exchanges -> exchanges.pathMatchers("/**").hasAnyRole("DIRECTOR")); }
application.yml:
spring.security.oauth2.client.provider.keycloak.issuer-uri: ..../realms/default
@Dave Thank you for reminding me this question. I have since found a workaround in WebFlux. I have overriden ReactiveOAuth2UserService. By default it has two flavors a OAuth one and a Oidc one. In my case I have overriden the Oidc one:
@Component public class ReactiveKeycloakUserService extends OidcReactiveOAuth2UserService {
@Override
public Mono<OidcUser> loadUser(OidcUserRequest userRequest) throws ... {
// Call super and then replace result with roles
}
}
Spring will inject my instance instead of the default one. From userRequest you can retrieve the roles and after calling the same method on superclass you can intercept the result and add the roles on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With