In my spring application, I would like a SecurityContextalways to contain Authentication. If it is not regular UsernamePasswordAuthenticationToken, it will be PreAuthenticatedAuthenticationTokendescribing 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 SecurityContextHolderStrategyand set it in SecurityContextHolderusingSecurityContextHolder.setStrategyName(MyStrategyClassName);
Now to the problem:
The default SecurityContextHolderStrategyis 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 ThreadLocalSecurityContextHolderStrategyinto my own SecurityContextHolderStrategyand implement the method the getContext()way I want. But it gives me the feeling that I'm wrong.
How can I reach the Authenticationdefault “system user” for a new one SecurityContext?
Update
, -, , , -. .
, spring.
, . ? , . ?