Summary
Using CompletableFuture<?> on secured API, SecurityContextHolder is not persisted on async handler.
Actual Behavior
With following controller method:
@GetMapping("/async")
CompletableFuture<String> async() {
return dummyService.async();
}
and ResponseBodyAdvice<T>
T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response);
If we try to use inside ResponseBodyAdvice
request.getPrincipal();
will return NULL
and
SecurityContextHolder.getContext().getAuthentication();
an anonymous user.
Expected Behavior
To be able to retrieve authentication that is generated before async is handle.
Configuration
See sample
Version
Using spring-boot version 1.4.1
Sample
https://github.com/kakawait/gh-ss-4087
mvn clean test
Comment From: kakawait
I just learned https://spring.io/guides/topicals/spring-security-architecture/#_processing_secure_methods_asynchronously
I will try that it may fix my problem
Comment From: eleftherias
It appears that the linked blog post helped answer the initial question. I will also link the latest reference documentatio on Async support for anyone still experiencing this issue.