I have some spring-boot
application (it exposes rest api). The mentioned REST API
is secured by spring-security
. Everything is fine, however now I need to set context
for servicing request. Setting context is about choosing datasource in depends on user context. The key is that RoutingDataSource need to use this context. (This context must be set directly after authenticating request due to other causes, I have also other thread which use RoutingDataSource, but no invoked by request (no user context)).
These things I can do, however my doubts are concerned on thread-safety of context and clearing it. I tried to find answer in docs, but I didn't managed to.
public class CustomContextHolder {
private static final ThreadLocal<DatabaseType> contextHolder =
new ThreadLocal<DatabaseType>();
public static void setContext(DatabaseType databaseType) {
contextHolder.set(databaseType);
}
public static CustomerType getContext() {
return (CustomerType) contextHolder.get();
}
public static void clearContext() {
contextHolder.remove();
}
}
And setting context:
@Component
class AuthorizedRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
// here we set context
}
filterChain.doFilter(request, response);
}
}
I can do it. However, because spring-boot
is multi-thread and I am using ThreadLocal
for hold context I am afraid of thread-safety of this configuration.
When I set this context ? In filter, only after successful authorization of request. So the questions are:
Is it thread-safe? It means: Can I assume that the same thread that executes filter (hence also this thread set context in its own local context) also executes entire request (e.g. calling methods from dao, sending response, executing body of controller) ?
If in case 1. I can assume that one thread works with request from begin to end (begin includes filter after secured request) then when I should call
clearContext()
?