Customize Authorization Code claims with Spring OAuth2 Authorization Server 3.2.4

58 Views Asked by At

I have the following flow with Keycloak and a service based on the Spring OAuth2 Authorization Server:

  • Keycloak delegates auth to Spring OAuth2 Authorization Server
  • Spring OAuth2 Authorization Server sends back using Authorization Grant Type request
  • Keycloak sends access token to a client

The access token contains some information about Principal from Authorization Server (name and email, for example) in the preferred_username claim:

"preferred_username":"given_name='markus',email='[email protected]'"

But I need these data in separate claims, something like this:

"given_name"="markus",
"email"="[email protected]",

The question how to pass these data in the Authorization Grant Type request from the Authorization Server to Keycloak, so Keycloak will be able to put/pass these data in the separate claims of access token?

In Authorization Server service I have the following:

Principal class

@Getter
@Setter
@AllArgsConstructor
public class User {
    private String givenName;
    private String email;

    @Override
    public String toString() {
        return "given_name='" + givenName + '\'' +
                ",email='" + email + '\'';
    }
}

A value generated by toString() somehow appears in the preferred_username claim of access token in Keycloak.

Auth provider

@Service
public class CustomAuthenticationProvider<T extends CustomAuthBean, A extends UsernamePasswordAuthenticationToken> implements AuthenticationProvider {
    User user = this.getUserDetails();
    return new UsernamePasswordAuthenticationToken(user, "", getAuthorities());
}

Configuration

@Configuration
public class SecurityConfig {
    @Bean
    @Order(1)
    SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
                .oidc(withDefaults());
        http
                .exceptionHandling((exceptions) -> exceptions
                        .defaultAuthenticationEntryPointFor(
                                new LoginUrlAuthenticationEntryPoint("/login"),
                                new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
                        )
                )
                .oauth2ResourceServer((resourceServer) -> resourceServer
                        .jwt(withDefaults()));

        return http.build();
    }
}

Please let me know if any more info is needed. Thank you in advance.

0

There are 0 best solutions below