eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

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",
        "[email protected]",
        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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest