1. Introduction

For most applications, user authentication is simply the first step to go through before providing any real services. In general, we need to associate the user identification with domain-specific information necessary to implement those services.

In this tutorial, we’ll show how to customize the Spring Authorization Server UserInfo endpoint handling, so client applications can get access to this information in a standard way.

2. What’s the OpenID Connect 1.0 UserInfo Endpoint?

The OpenID Connect specification adds an identity layer on top of the OAuth 2.0 standard, which allows identity providers, or IdP for short, to provide clients with identity information in two ways:

  • id_token: a JWT, handed to a client as part of the authentication flow, containing a set of user attributes – also known as claims – in the token’s payload
  • UserInfo endpoint: an optional endpoint, though largely supported by current implementations, that returns user claims either as a JSON object or a signed and/or encrypted JWT

While similar in content, there are some technical and semantic differences between them:

id_token UserInfo endpoint
Delivery authorization callback or token endpoint GET (recommended) or POST request to the IdP using the access_token received as part of the authorization flow
Required claims iss (issuer), aud (audience), sub (subject), exp (expiration time), iat (issuance time) sub, but iss and aud are also mandatory when the response is a signed JWT
Security attributes JWT Signature with optional encryption; optional login details claims(acr, amr, etc) Signature and encryption are optional
Primary use case authentication-related and minimal user identity attributes full profile information

Besides the required claims, the specification also defines a set of standard claims which, in many cases, are enough to populate an application account with user details. The key difference is when we use each method.

For the id_token, the attributes represent a snapshot taken at authentication time, and once issued, the only reliable and portable way to get an updated version is to go through a full authorization flow. The exception to this rule is when the IdP supports returning the id_token when returning a new access_token from a refresh_token request.

In contrast, a client application can use the UserInfo endpoint whenever it wants to get the most recent version of the data, making it a go-to choice when implementing “My Profile” pages or similar functionality. Another relevant scenario is when the client application calls a backend resource server that requires some user profile attribute not already present in the access_token. In this case, the backend uses the received token to query the UserInfo endpoint, possibly caching it to avoid extra delays in subsequent calls.

3. Spring Authorization Server Default Implementation

We’ve already covered the basics of the Spring Authorization Server (SAS for short) in previous tutorials, so we won’t go into much detail here. As a quick reminder, since Spring Security 7 and Spring Boot 4, SAS is no longer a standalone project but a standard module within those frameworks.

Here are the required Maven dependencies for our WebMVC-based project:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security-oauth2-authorization-server</artifactId> <version>4.0.5</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security-oauth2-authorization-server-test</artifactId> <version>4.0.5</version> <scope>test</scope> </dependency> 

The latest versions of these dependencies are available on Maven Central:

• spring-boot-starter-security-oauth2-authorization-server
• spring-boot-starter-security-oauth2-authorization-server-test

Let’s start by creating a minimal Spring Security configuration to see what we get “out-of-the-box”:

@Bean @Order(Ordered.HIGHEST_PRECEDENCE) SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) { return http.oauth2AuthorizationServer(sas -> { http .securityMatcher(sas.getEndpointsMatcher()) .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()) .exceptionHandling(exceptions -> exceptions.defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), createRequestMatcher())); sas.oidc(withDefaults()); }).build(); } @Bean @Order(SecurityFilterProperties.BASIC_AUTH_ORDER) SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) { http .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()) .formLogin(withDefaults()); return http.build(); } 

We also need a test client and user, which we’ll provide using this YAML configuration:

spring: security: user: name: user password: "{noop}password" oauth2: authorizationserver: client: client1: require-proof-key: false require-authorization-consent: false registration: client-name: "Client 1 - Issuer 1" client-id: client1 client-secret: "{noop}secret1" client-authentication-methods: - client_secret_basic redirect-uris: - http://localhost:9090/login/oauth2/code/issuer1client1 authorization-grant-types: - authorization_code - refresh_token scopes: - openid - email - profile - account

The test client, available online, goes through the following steps to get the UserInfo response:

  • Fetch and parse the OIDC discovery document to find the required endpoints
  • Start an authentication flow which includes the custom account  scope and submit the login form using the test credentials
  • Use the authorization code to get the access and id tokens
  • Use the access token to retrieve the userinfo data

Running the test shows that the only available claim is sub, which contains the username used to log into the application. This is expected, as this is the only information provided by the underlying authentication mechanism.

4. UserInfo Service Implementation

Before we can add any claim, we need to define a source for it. The idea is to decouple the information retrieval aspect from the UserInfo response customization. This approach has the added benefit that it makes it easy to reuse this service to customize the id_token generation.

Our service contains a single method that, given a username, returns a record with the attributes we’ll add:

@Service public class UserInfoService { static final Map<String, UserInfo> users = Map.of( "user", new UserInfo( "user", "Alice Smith", "Alice", "Smith", "alice.smith@example.com", true, Locale.forLanguageTag("en-US"), "female", LocalDate.of(1990, 1, 1), ZoneId.of("America/New_York"), UUID.randomUUID(), Instant.now(), Instant.now(), Instant.now().plus(60, java.time.temporal.ChronoUnit.DAYS) ) ); public Optional<UserInfo> getUserInfoByUsername(String username) { return Optional.ofNullable(users.get(username)); } public record UserInfo( String username, String name, String givenName, String familyName, String email, boolean emailVerified, Locale locale, String gender, LocalDate birthdate, ZoneId zoneId, UUID accountId, Instant createdAt, Instant updatedAt, Instant accountExpiresAt ) {} } 

Here, the implementation just looks up the username in a static map and returns the associated information record. A real-world implementation would use some repository to get this information, like a database, LDAP, or a REST service.

We’ve also added the @Service annotation to the class, which allows Spring to automatically add it to the application context. In turn, this allows us to inject the service where needed, as we’ll see in the next section.

5. UserInfo Mapping

To use UserInfoService with SAS, we must implement a Function that maps an OidcUserInfoAuthenticationContext instance to an OidcUserInfo object. The SAS-provided OidcUserInfoAuthenticationContext contains the following fields:

  • authentication: a valid Authentication associated with the request. We can use getName() to get the username associated with the request
  • authorization: The OAuth 2.0 authorization used to generate the access token sent to the client.
  • accessToken: The received access token, which can be useful if we want to access downstream protected resources

The authorization contains the client’s authorized scopes, with which we filter the information returned from UserInfoService while building the final OidcUserInfo instance.

The UserInfoMapper class implements this:

public class UserInfoMapper implements Function<OidcUserInfoAuthenticationContext, OidcUserInfo> { private final UserInfoService userInfoService; // ... constructor omitted @Override public OidcUserInfo apply(OidcUserInfoAuthenticationContext context) { var auth = context.getAuthentication(); var subject = auth.getName(); var scopes = context.getAuthorization().getAuthorizedScopes(); var userInfo = userInfoService.getUserInfoByUsername(subject); if ( userInfo.isEmpty() || scopes.isEmpty() || (scopes.size() == 1 && scopes.contains("openid")) ) { return OidcUserInfo.builder() .subject(subject) .build(); } var user = userInfo.get(); var b = OidcUserInfo.builder().subject(subject); if ( scopes.contains("email") ) { b.email(user.email()) .emailVerified(user.emailVerified()); } if( scopes.contains("profile") ) { b.name(user.name()) .givenName(user.givenName()) .familyName(user.familyName()) .locale(user.locale().toLanguageTag()) .gender(user.gender()) .birthdate(user.birthdate().toString()) .zoneinfo(user.zoneId().toString()) .preferredUsername(user.username()) .claim(StandardClaimNames.UPDATED_AT, user.updatedAt().getEpochSecond()); } if ( scopes.contains("account") ) { b.claim("account_id", user.accountId().toString()) .claim("created_at", user.createdAt().getEpochSecond()) .claim("account_expires_at", user.accountExpiresAt().getEpochSecond()); } return b.build(); } } 

Notice that, for the updated_at claim, we’re not using the builder’s updatedAt method. The reason is that Spring, at least in its current version, outputs this claim as a string instead of a JSON number. As a workaround, we use the generic claim() method, which accept any object as the claim’s value.

Here, we have a small fixed list of scopes, which allows us to use a simple set of “if” statements for building the OidcUserInfo instance. For a larger set of scopes, we need a more structured approach. For instance, we could use a map from scopes to “claim populators” responsible for mapping attributes from the user’s value object to OidcUserInfo.

6. Registering the UserInfo Mapping

The final step we need to take is to configure SAS with our custom mapper. This is done in the oidc configurer accessible in the authorization server’s DSL:

@Bean @Order(Ordered.HIGHEST_PRECEDENCE) SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http, UserInfoMapper userInfoMapper) { return http.oauth2AuthorizationServer(sas -> { http .securityMatcher(sas.getEndpointsMatcher()) .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()) .exceptionHandling(exceptions -> exceptions.defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), createRequestMatcher())); if (enableCustomUserInfo) { sas.oidc(oidc -> oidc .userInfoEndpoint(userInfo -> userInfo .userInfoMapper(userInfoMapper))); } else { sas.oidc(withDefaults()); } }).build(); } 

For illustration/testing purposes only, we’ve conditionally configured our custom mapper using a feature flag (enableCustomUserInfo). This allows us to quickly enable/disable this functionality through the customuserinfo.enabled property and compare the results.

7. Testing the Complete Flow

We complete the coding for this tutorial with a unit test that goes through the authentication flow and uses the resulting access token to query the UserInfo endpoint.

The full code, available online, is mostly identical to what we’ve presented here, with the following differences:

  • We ensure that the customuserinfo.enabled property is set to true
  • Extra assert statements at the end to check the presence of the custom claims

To get a better understanding of SAS’s inner workings, a good approach is to run the unit test from an IDE and set breakpoints at key points. One of them is the UserInfoService implementation. Once the test reaches the getUserInfoByUsername() method, we can walk back the call stack up to the OidcUserInfoEndpointFilter, where we’ll be able to see how the authentication/authorization components collaborate.

8. Other Available Customizations

SAS’s customization possibilities do not stop at adding extra claims, though this is the most common scenario.

The oidc DSL, as it is the case with other endpoints, allows developers to take full control of the endpoint’s processing. Although not covered in this tutorial, let’s briefly describe them:

  • userInfoRequestConverter: adds a custom request converter, which converts an HttpServletRequest to an Authentication
  • userInfoRequestConverters: allows us to add, remove, or modify the list of authentication converters
  • authenticationProvider: adds a custom authentication provider to the list of available providers used to authenticate a request
  • authenticationProviders: allows us to add, remove, or modify authentication providers
  • userInfoResponseHandler: replace the logic used to generate the final response sent to clients
  • errorResponseHandler: replace the logic used to generate the response sent to clients in case of error.

Together, those methods allow us to handle any custom requirements related to the request processing. For example, if we wanted to encrypt the response or use a custom authentication method, we’d use the appropriate methods to replace the standard processing with our custom one.

9. Conclusion

In this tutorial, we’ve shown how to customize the Spring Authorization Server’s UserInfo endpoint, so the response includes extra claims retrieved from a developer-supplied service.

As always, the full source code is available over on GitHub.

The post Customize the OpenID Connect 1.0 UserInfo Response in Spring Authorization Server first appeared on Baeldung.