Vuk Djapic
Vuk Djapic

Reputation: 886

How to get Keycloak realm and user attributes in Spring Cloud Gateway

In Spring Boot with MVC it was possible to get information about Keycloak user realm and defined attributes through injected Principal in controller method, which was of type KeycloakAuthenticationToken, which provides this information.

But in Spring Cloud Gateway with dependencies

    implementation 'org.springframework.cloud:spring-cloud-security'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

and security defined through

public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
            ReactiveClientRegistrationRepository clientRegistrationRepository) {
        // Authenticate through configured OpenID Provider
        http.oauth2Login();
        ...
}

security works and I managed to retrieve Principal through a filter

.filter((exchange, chain) -> {

                            return exchange.getPrincipal().flatMap(p -> {
                                System.out.println("Pricnipal class: " + p.getClass());
                                OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) p;
                                System.out.println("Token: " + token.getAuthorizedClientRegistrationId() + "|"
                                        + token.getPrincipal().getAttributes() + "|" + token.getDetails() + "|"+ token.getPrincipal().getClass());
                                System.out.println("Exchange Attr: " + exchange.getAttributes());
                                OidcUser oicdUser = (OidcUser)token.getPrincipal();
                                System.out.println("OicdUser: "+oicdUser.getClaims()+ "|" + oicdUser.getIdToken().getClaims()+"|"+oicdUser.getAttributes());
                                Authentication aut = (Authentication) p;
                                ServerHttpRequest request = exchange.getRequest().mutate().header("username1", p.getName())
                                        .header("roles1", aut.getAuthorities().toString()).build();
                                return chain.filter(exchange.mutate().request(request).build());
                            });

                        })

But its type is OAuth2AuthenticationToken. And there is basic info in it about authenticated user, but no Keycloak realm or user attributes data defined through Keycloak admin console.

Upvotes: 2

Views: 2062

Answers (1)

Vuk Djapic
Vuk Djapic

Reputation: 886

Actually, it works. There is nothing wrong with posted code. I didn't set Keycloak Mappers properly, which is needed to add attributes to token. With that configured, above method is enough to retrieve user attributes from the token. They will be in token.getPrincipal().getAttributes() property of OAuth2AuthenticationToken token.

Upvotes: 1

Related Questions