I have a Spring Boot application that provides a REST API and is using cognito and oauth2-resource-server.

My resources are protected and work correctly when accessed with the access_token. I have this common SecurityConfig:

@Configuration
public class JWTSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(authz -> authz.antMatchers(HttpMethod.GET, "/foos/**")
            .hasAuthority("SCOPE_read")
            .antMatchers(HttpMethod.POST, "/foos")
            .hasAuthority("SCOPE_write")
            .anyRequest()
            .authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt());
        return http.build();
    }
}

However, I need to fetch additional user information, such as name and email, which are available in either the userInfo endpoint or id_token (not access_token).

Currently, as a workaround, I'm making a RestTemplate HTTP call to the userinfo endpoint https://{{user_pool_domain}}.auth.{{region}}.amazoncognito.com/oauth2/userinfo to retrieve this information.

However, I believe Spring may have a built-in way to handle this automatically, possibly with cache management.

How can I achieve this user information without hardcoding the HTTP call?

1

There are 1 best solutions below

0
On

I have written a tutorial with an other approach: have the client send the ID token in addition to the access token (in a different header) and then have Spring Security validate both tokens and build Authentication instance using both set of claims (from access and ID tokens).

This is useful for Cognito for which you can customize only ID token claims and much more efficient than calling Cognito for each incoming request to your resource server(s).