In my spring application, I would like a SecurityContext
always to contain Authentication
. If it is not regular UsernamePasswordAuthenticationToken
, it will be PreAuthenticatedAuthenticationToken
describing the "system user". This has reasons within the various system function that the user requires. To avoid special treatment if there is no user context, I just want to add a system context. IMHO, this is also associated with the principle of single responsibility.
To achieve this, I can simply implement my own SecurityContextHolderStrategy
and set it in SecurityContextHolder
usingSecurityContextHolder.setStrategyName(MyStrategyClassName);
Now to the problem:
The default SecurityContextHolderStrategy
is ThreadLocalSecurityContextHolderStrategy
. I am pleased with this strategy and the way it works. The only thing I would change is the method getContext()
.
public SecurityContext getContext() {
SecurityContext ctx = CONTEXT_HOLDER.get();
if (ctx == null) {
ctx = createEmptyContext();
CONTEXT_HOLDER.set(ctx);
}
return ctx;
}
to
public SecurityContext getContext() {
SecurityContext ctx = CONTEXT_HOLDER.get();
if (ctx == null) {
ctx = createEmptyContext();
Authentication authentication = new PreAuthenticatedAuthenticationToken("system", null);
authentication.setAuthenticated(true);
ctx.setAuthentication(authentication);
CONTEXT_HOLDER.set(ctx);
}
return ctx;
}
This is not , because the class is ThreadLocalSecurityContextHolderStrategy
notpublic
. Of course, I can just copy the code ThreadLocalSecurityContextHolderStrategy
into my own SecurityContextHolderStrategy
and implement the method the getContext()
way I want. But it gives me the feeling that I'm wrong.
How can I reach the Authentication
default “system user” for a new one SecurityContext
?
Update
, -, , , -. .
, spring.
, . ? , . ?