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 SECURITYMocking 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:
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:
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:
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:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
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:
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:
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.
1. Introduction
In this quick tutorial, weβre going to focus on the Servlet 3 support for async requests, and how Spring MVC and Spring Security handle these.
The most basic motivation for asynchronicity in web applications is to handle long running requests. In most use cases, weβll need to make sure the Spring Security principal is propagated to these threads.
And, of course, Spring Security integrates with @Async outside the scope of MVC and processing HTTP requests as well.
2. Maven Dependencies
In order to use the async integration in Spring MVC, we need to include the following dependencies into our pom.xml:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>6.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>6.1.5</version>
</dependency>
The latest version of Spring Security dependencies can be found here.
3. Spring MVC and @Async
According to the official docs, Spring Security integrates with WebAsyncManager.
The first step is to ensure our springSecurityFilterChain is set up for processing asynchronous requests. We can do it either in Java config, by adding following line to our Servlet config class:
dispatcher.setAsyncSupported(true);
or in XML config:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ASYNC</dispatcher>
</filter-mapping>
We also need to enable the async-supported parameter in our servlet configuration:
<servlet>
...
<async-supported>true</async-supported>
...
</servlet>
Now we are ready to send asynchronous requests with SecurityContext propagated with them.
Internal mechanisms within Spring Security will ensure that our SecurityContext is no longer cleared out when a response is committed in another Thread resulting in a user logout.
4. Use Cases
Letβs see this in action with a simple example:
@Override
public Callable<Boolean> checkIfPrincipalPropagated() {
Object before
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.info("Before new thread: " + before);
return new Callable<Boolean>() {
public Boolean call() throws Exception {
Object after
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.info("New thread: " + after);
return before == after;
}
};
}
We want to check if the Spring SecurityContext is propagated to the new thread.
The method presented above will automatically have its Callable executed with the SecurityContext included, as seen in logs:
web - 2017-01-02 10:42:19,011 [http-nio-8081-exec-3] INFO
o.baeldung.web.service.AsyncService - Before new thread:
org.springframework.security.core.userdetails.User@76507e51:
Username: temporary; Password: [PROTECTED]; Enabled: true;
AccountNonExpired: true; credentialsNonExpired: true;
AccountNonLocked: true; Granted Authorities: ROLE_ADMIN
web - 2017-01-02 10:42:19,020 [MvcAsync1] INFO
o.baeldung.web.service.AsyncService - New thread:
org.springframework.security.core.userdetails.User@76507e51:
Username: temporary; Password: [PROTECTED]; Enabled: true;
AccountNonExpired: true; credentialsNonExpired: true;
AccountNonLocked: true; Granted Authorities: ROLE_ADMIN
Without setting up the SecurityContext to be propagated, the second request will end up with null value.
There are also other important use cases to use asynchronous requests with propagated SecurityContext:
- we want to make multiple external requests which can run in parallel and which may take significant time to execute
- we have some significant processing to do locally and our external request can execute in parallel to that
- other represent fire-and-forget scenarios, like for example sending an email
Do note that, if our multiple method calls were previously chained together in a synchronous fashion, converting these to an asynchronous approach may require synchronizing results.
5. Conclusion
In this short tutorial, we illustrated the Spring support for processing asynchronous requests in an authenticated context.
From a programming model perspective, the new capabilities appear deceptively simple. But there are certainly some aspects that do require a more in-depth understanding.
