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 – LJB – NPI EA (cat = Core Java)
announcement - icon

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

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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

Spring Security version 6.3 has introduced a range of security enhancements in the framework.

In this tutorial, we’ll discuss some of the most notable features, highlighting their benefits and usage.

2. Passive JDK Serialization Support

Spring Security 6.3 included passive JDK serialization support. However, before we discuss this further, let’s understand the problem and issues surrounding it.

2.1. Spring Security Serialization Design

Before version 6.3, Spring Security had a strict policy regarding serialization and deserialization of its classes across different versions through JDK serialization. This restriction was a deliberate design decision by the framework to ensure security and stability. The rationale was to prevent incompatibilities and security vulnerabilities from deserializing objects serialized in one version using a different version of Spring Security.

One key aspect of this design is the usage of a global serialVersionUID for the entire Spring Security project. In Java, the serialization and deserialization process uses a unique identifier serialVersionUID to verify that a loaded class corresponds exactly to a serialized object.

By maintaining a global serialVersionUID unique to each release version of Spring Security, the framework ensures that serialized objects from one version cannot be deserialized using another version. This approach effectively creates a version barrier, preventing the deserialization of objects with mismatched serialVersionUID values.

For example, the SecurityContextImpl class in Spring Security represents security context information. The serialized version of this class includes the serialVersionUID specific to that version. When attempting to deserialize this object in a different version of Spring Security, the serialVersionUID mismatch prevents the process from succeeding.

2.2. Challenges Arising from the Serialization Design

While prioritizing enhanced security, this design policy also introduces several challenges. Developers commonly integrate Spring Security with other Spring libraries, such as Spring Session, to manage user login sessions. These sessions encompass crucial user authentication and security context information, typically implemented through Spring Security classes. Furthermore, to optimize user experience and enhance application scalability, developers often store this session data across various persistent storage solutions, including databases.

The following are some of the challenges that arise due to the serialization design. Upgrading applications through the Canary release process can lead to an issue if the Spring Security version changes. In such cases, the persisted session information cannot be deserialized, potentially necessitating users to re-login.

Another issue arises in application architectures utilizing Remote Method Invocation (RMI) with Spring Security. For instance, if the client application employs Spring Security classes in a remote method call, it must serialize them on the client side and deserialize them on the other side. If both applications do not share the same Spring Security version, this invocation fails, resulting in an InvalidClassException exception.

2.3. Workarounds

The typical workarounds for this issue are as follows. We can use a different serialization library other than JDK Serialization, such as Jackson Serialization. With this, instead of serializing the Spring Security class, we obtain a JSON representation of the required details and serialize it with Jackson.

Another option is to extend the required Spring Security class, such as Authentication, and explicitly implement custom serialization support through the readObject and writeObject methods.

2.4. Serialization Changes in Spring Security 6.3

With version 6.3, class serialization undergoes a compatibility check with the preceding minor version. This ensures that upgrading to newer versions allows the deserialization of Spring Security classes seamlessly.

3. Authorization

Spring Security 6.3 has introduced a few notable changes in the Spring Security Authorization. Let us explore these in this section.

3.1. Annotation Parameters

Spring Security’s method security supports meta-annotations. We can take an annotation and improve it’s readability based on the application’s use case. For instance, we can simplify the @PreAuthorize(“hasRole(‘USER’)”) to the following:

@Target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('USER')")
public @interface IsUser {
    String[] value();
}

Next, we can use this @IsUser annotation in the business code:

@Service
public class MessageService {
    @IsUser
    public Message readMessage() {
        return "Message";
    }
}

Let’s assume we have another role, ADMIN. We can create an annotation named @IsAdmin for this role. However, this would be redundant. It would be more appropriate to use this meta-annotation as a template and include the role as an annotation parameter. Spring Security 6.3 introduces the ability to define such meta-annotations. Let us demonstrate this with a concrete example:

To template a meta-annotation, first, we need to define a bean PrePostTemplateDefaults:

@Bean
PrePostTemplateDefaults prePostTemplateDefaults() {
    return new PrePostTemplateDefaults();
}

This bean definition is required for the template resolution.

Next, we’ll define a meta-annotation @CustomHasAnyRole for the @PreAuthorize annotation that can accept both USER and ADMIN roles:

@Target({ ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasAnyRole({value})")
public @interface CustomHasAnyRole {
    String[] value();
}

We can use this meta-annotation by supplying the roles:

@Service
public class MessageService {
    private final List<Message> messages;

    public MessageService() {
        messages = new ArrayList<>();
        messages.add(new Message(1, "Message 1"));
    }
    
    @CustomHasAnyRole({"'USER'", "'ADMIN'"})
    public Message readMessage(Integer id) {
        return messages.get(0);
    }

    @CustomHasAnyRole("'ADMIN'")
    public String writeMessage(Message message) {
        return "Message Written";
    }
    
    @CustomHasAnyRole({"'ADMIN'"})
    public String deleteMessage(Integer id) {
        return "Message Deleted";
    }
}

In the above example, we supplied the role values – USER and ADMIN as the annotation parameter.

3.2. Securing Return Values

Another powerful new feature in Spring Security 6.3 is the ability to secure domain objects using the @AuthorizeReturnObject annotation. This enhancement allows for more granular security by enabling authorization checks on the objects returned by methods, ensuring that only authorized users can access specific domain objects.

Let us demonstrate this with an example. Let’s say we have the following Account class with the iban and balance fields. The requirement is that only users with read authority can retrieve the account balance.

public class Account {
    private String iban;
    private Double balance;

    // Constructor

    public String getIban() {
        return iban;
    }

    @PreAuthorize("hasAuthority('read')")
    public Double getBalance() {
        return balance;
    }
}

Next, let us define the AccountService class, which returns an account instance:

@Service
public class AccountService {
    @AuthorizeReturnObject
    public Optional<Account> getAccountByIban(String iban) {
        return Optional.of(new Account("XX1234567809", 2345.6));
    }
}

In the above snippet, we have used the @AuthorizeReturnObject annotation. Spring security ensures that the Account instance can only be accessed by the user with read authority.

3.3. Error Handling

In the section above, we discussed using the @AuthorizeReturnObject annotation to secure the domain objects. Once enabled, the unauthorized access results in an AccessDeniedException. Spring Security 6.3 provides the MethodAuthorizationDeniedHandler interface to handle authorization failures.

Let us demonstrate this with an example. Let us extend the example in section 3.2 and secure the IBAN with the read authority. However, we intend to provide a masked value instead of returning an AccessDeniedException for any unauthorized access.

Let us define an implementation of the MethodAuthorizationDeniedHandler interface:

@Component
public class MaskMethodAuthorizationDeniedHandler implements MethodAuthorizationDeniedHandler  {
    @Override
    public Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) {
        return "****";
    }
}

In the above snippet, we provided a masked value if there is an AccessDeniedException. This handler class can be used in the getIban() method, as shown below:

@PreAuthorize("hasAuthority('read')")
@HandleAuthorizationDenied(handlerClass=MaskMethodAuthorizationDeniedHandler.class)
public String getIban() {
    return iban;
}

4. Compromised Password Checking

Spring Security 6.3 provides an implementation for compromised password checks. This implementation checks a provided password against a compromised password database (pwnedpasswords.com). Therefore, applications can verify the user-provided password at registration time. The following code snippets demonstrate the usage.

First, define a bean definition of HaveIBeenPwnedRestApiPasswordChecker class:

@Bean
public HaveIBeenPwnedRestApiPasswordChecker passwordChecker() {
    return new HaveIBeenPwnedRestApiPasswordChecker();
}

Next, use this implementation to check the user-provided password:

@RestController
@RequestMapping("/register")
public class RegistrationController {
    private final HaveIBeenPwnedRestApiPasswordChecker haveIBeenPwnedRestApiPasswordChecker;

    @Autowired
    public RegistrationController(HaveIBeenPwnedRestApiPasswordChecker haveIBeenPwnedRestApiPasswordChecker) {
        this.haveIBeenPwnedRestApiPasswordChecker = haveIBeenPwnedRestApiPasswordChecker;
    }

    @PostMapping
    public String register(@RequestParam String username, @RequestParam String password) {
        CompromisedPasswordDecision compromisedPasswordDecision = haveIBeenPwnedRestApiPasswordChecker.checkPassword(password);
        if (compromisedPasswordDecision.isCompromised()) {
	    throw new IllegalArgumentException("Compromised Password.");
	}

        // ...
        return "User registered successfully";
    }
}

5. OAuth 2.0 Token Exchange Grant

Spring Security 6.3 also introduced support for the OAuth 2.0 Token Exchange (RFC 8693) grant, allowing clients to exchange tokens while retaining the user’s identity. This feature enables scenarios like impersonation, where a resource server can act as a client to obtain new tokens. Let us elaborate on this with an example.

Let’s assume we have a resource server named loan-service, which provides various APIs for loan accounts. This service is secured, and clients need to supply an access token that must have the audience (aud claim) of the loan service.

Let’s now imagine that loan-service needs to invoke another resource service loan-product-service which exposes details for loan products. The loan-product-service is also secure and requires tokens that must have the audience of the loan-product-service. Since the audience is different in these two services, the token for loan service can’t be used for loan-product-service.

In this case, the resource server, loan-service should become a client and exchange the existing token for a new token for loan-product-service that retains the the original token identity.

Spring Security 6.3 provides a new implementation of the OAuth2AuthorizedClientProvider class named TokenExchangeOAuth2AuthorizedClientProvider for the token-exchange grant.

6. Conclusion

In this article, we discussed various new features introduced in Spring Security 6.3.

The notable changes are enhancement to the authorization framework, passive JDK serialization support, and OAuth 2.0 Token Exchange support.

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 – 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)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments