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 – 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 – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

Adding custom claims to JSON Web Token (JWT) access tokens can be crucial in many scenarios. Custom claims allow us to include additional information in the token payload.

In this tutorial, we’ll learn how to add resource owner authorities to a JWT access token in the Spring Authorization Server.

2. Spring Authorization Server

The Spring Authorization Server is a new project in the Spring ecosystem designed to provide Authorization Server support to Spring applications. It aims to simplify the process of implementing OAuth 2.0 and OpenID Connect (OIDC) authorization servers using the familiar and flexible Spring programming model.

2.1. Maven Dependencies

Let’s start by importing the spring-boot-starter-web, spring-boot-starter-security, spring-boot-starter-test, and spring-security-oauth2-authorization-server dependencies to the pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.5.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>2.5.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-authorization-server</artifactId>
    <version>0.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.5.4</version>
</dependency>

Alternatively, we can add the spring-boot-starter-oauth2-authorization-server dependency to our pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
    <version>3.2.0</version>
</dependency>

2.2. Project Setup

Let’s set up the Spring Authorization Server for issuing access tokens. To keep things simple, we’ll be using the Spring Security OAuth Authorization Server application.

Let’s assume that we’re using the authorization server project available on GitHub.

3. Add Basic Custom Claims to JWT Access Tokens

In a Spring Security OAuth2-based application, we can add custom claims to JWT access tokens by customizing the token creation process in the Authorization Server. This type of claim can be useful for injecting additional information into JWTs, which can then be used by resource servers or other components in the authentication and authorization flow.

3.1. Add Basic Custom Claims

We can add our custom claims to an access token using the OAuth2TokenCustomizer<JWTEncodingContext> bean. By using it, every access token that is issued by the authorization server will have the custom claims populated.

Let’s add the OAuth2TokenCustomizer bean in the DefaultSecurityConfig class:

@Bean
@Profile("basic-claim")
public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer() {
    return (context) -> {
      if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
        context.getClaims().claims((claims) -> {
          claims.put("claim-1", "value-1");
          claims.put("claim-2", "value-2");
        });
      }
    };
}

The OAuth2TokenCustomizer interface is part of the Spring Security OAuth2 library and is used to customize OAuth 2.0 tokens. In this case, it specifically customizes JWT tokens during the encoding process. 

The lambda expression passed to the jwtTokenCustomizer() bean defines the customization logic. The context parameter represents the JwtEncodingContext during the token encoding process. 

First, we use the context.getTokenType() method to check whether the token being processed is an access token. Then, we obtain the claims associated with the JWT being constructed by using the context.getClaims() method. Finally, we add custom claims to the JWT.

In this example, two claims (“claim-1” and “claim-2“) with corresponding values (“value-1” and “value-2“) are added.

3.2. Test the Custom Claims

For testing, we are going to use the client_credentials grant type. 

First, we’ll define the client_credentials grant type from AuthorizationServerConfig as an authorized grant type in the RegisteredClient object:

@Bean
public RegisteredClientRepository registeredClientRepository() {
    RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
      .clientId("articles-client")
      .clientSecret("{noop}secret")
      .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
      .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
      .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
      .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
      .redirectUri("http://127.0.0.1:8080/login/oauth2/code/articles-client-oidc")
      .redirectUri("http://127.0.0.1:8080/authorized")
      .scope(OidcScopes.OPENID)
      .scope("articles.read")
      .build();

    return new InMemoryRegisteredClientRepository(registeredClient);
}

Then, let’s create a test case in the CustomClaimsConfigurationTest class:

@ActiveProfiles(value = "basic-claim")
public class CustomClaimsConfigurationTest {

    private static final String ISSUER_URL = "http://localhost:";
    private static final String USERNAME = "articles-client";
    private static final String PASSWORD = "secret";
    private static final String GRANT_TYPE = "client_credentials";

    @Autowired
    private TestRestTemplate restTemplate;

    @LocalServerPort
    private int serverPort;

    @Test
    public void givenAccessToken_whenGetCustomClaim_thenSuccess() throws ParseException {
        String url = ISSUER_URL + serverPort + "/oauth2/token";
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(USERNAME, PASSWORD);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", GRANT_TYPE);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<TokenDTO> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, TokenDTO.class);

        SignedJWT signedJWT = SignedJWT.parse(response.getBody().getAccessToken());
        JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
        Map<String, Object> claims = claimsSet.getClaims();

        assertEquals("value-1", claims.get("claim-1"));
        assertEquals("value-2", claims.get("claim-2"));
    } 
    
    static class TokenDTO {
        @JsonProperty("access_token")
        private String accessToken;
        @JsonProperty("token_type")
        private String tokenType;
        @JsonProperty("expires_in")
        private String expiresIn;
        @JsonProperty("scope")
        private String scope;

        public String getAccessToken() {
            return accessToken;
        }
    }
}

Let’s walk through the key parts of our test to understand what is going on:

  • Start by constructing a URL for the OAuth2 token endpoint.
  • Retrieve a response containing the TokenDTO class from a POST request to the token endpoint. Here, we create an HTTP request entity with headers (basic authentication) and parameters (grant type).
  • Parse the Access Token from the response using the SignedJWT class. Also, we extract claims from the JWT and store them in the Map<String, Object>.
  • Assert that specific claims in the JWT have expected values using JUnit assertions.

This test confirms that our token encoding process is working properly and our claims are being generated as expected. Awesome!

In addition, we can get the access token using the curl command: 

curl --request POST \
  --url http://localhost:9000/oauth2/token \
  --header 'Authorization: Basic YXJ0aWNsZXMtY2xpZW50OnNlY3JldA==' \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data grant_type=client_credentials

Here, the credentials are encoded as a Base64 string of the client ID and client secret, delimited by a single colon “:”.

Now, we can run our Spring Boot application with the profile basic-claim.

If we obtain an access token and decode it using jwt.io, we find the test claims in the token’s body:

{
  "sub": "articles-client",
  "aud": "articles-client",
  "nbf": 1704517985,
  "scope": [
    "articles.read",
    "openid"
  ],
  "iss": "http://auth-server:9000",
  "exp": 1704518285,
  "claim-1": "value-1",
  "iat": 1704517985,
  "claim-2": "value-2"
}

As we can see, the value of the test claims is as expected.

We’ll discuss adding authority as claims to access tokens in the following section.

4. Add Authorities as Custom Claims to JWT Access Tokens

Adding authorities as custom claims to JWT access tokens is often a crucial aspect of securing and managing access in a Spring Boot application. Authorities, typically represented by GrantedAuthority objects in Spring Security, indicate what actions or roles a user is allowed to perform. By including these authorities as custom claims in JWT access tokens, we provide a convenient and standardized way for resource servers to understand the user’s permissions.

4.1. Add Authorities as Custom Claims

First, we use a simple in-memory user configuration with a set of authorities in the DefaultSecurityConfig class:

@Bean
UserDetailsService users() {
    UserDetails user = User.withDefaultPasswordEncoder()
      .username("admin")
      .password("password")
      .roles("USER")
      .build();
    return new InMemoryUserDetailsManager(user);
}

A single user with the username “admin” password “password” and role “USER” is created.

Now, let’s populate a custom claim in the access token with those authorities:

@Bean
@Profile("authority-claim")
public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer(@Qualifier("users") UserDetailsService userDetailsService) {
    return (context) -> {
      UserDetails userDetails = userDetailsService.loadUserByUsername(context.getPrincipal().getName());
      Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
      context.getClaims().claims(claims ->
         claims.put("authorities", authorities.stream().map(authority -> authority.getAuthority()).collect(Collectors.toList())));
    };
}

First, we define a lambda function that implements the OAuth2TokenCustomizer<JwtEncodingContext> interface. This function customizes the JWT during the encoding process.

Then, we retrieve the UserDetails object associated with the current principal (user) from the injected UserDetailsService. The principal’s name is typically the username.

After that, we retrieve the collection of GrantedAuthority objects associated with the user. 

Finally, we retrieve the JWT claims from the JwtEncodingContext and apply customizations. It includes adding a custom claim named “authorities” to the JWT. Also, this claim contains a list of authority strings obtained from the GrantedAuthority objects associated with the user. 

4.2. Test the Authorities Claims

Now that we’ve configured the authorization server, let’s test it. For that, we’ll use the client-server project from the same GitHub folder.

Let’s create a REST API client that will fetch the list of claims from the access token:

@GetMapping(value = "/claims")
public String getClaims(
  @RegisteredOAuth2AuthorizedClient("articles-client-authorization-code") OAuth2AuthorizedClient authorizedClient
) throws ParseException {
    SignedJWT signedJWT = SignedJWT.parse(authorizedClient.getAccessToken().getTokenValue());
    JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
    Map<String, Object> claims = claimsSet.getClaims();
    return claims.get("authorities").toString();
}

The @RegisteredOAuth2AuthorizedClient annotation is used in a Spring Boot controller method to indicate that the method expects an OAuth 2.0 authorized client to be registered with the specified client ID. In this case, the client ID is “articles-client-authorization-code“.

Let’s run our Spring Boot application with the profile authority-claim.

Now when we go into the browser and try to access the http://127.0.0.1:8080/claims page, we’ll be automatically redirected to the OAuth server login page under http://auth-server:9000/login URL.

After providing the proper username and password, the authorization server will redirect us back to the requested URL, the list of claims.

5. Conclusion

Overall, the ability to add custom claims to JWT access tokens provides a powerful mechanism for tailoring tokens to the specific needs of our application and enhancing the overall security and functionality of our authentication and authorization system.

In this article, we learned how to add custom claims and user authorities to a JWT access token in the Spring Authorization Server.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
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

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

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 – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)