title: SecurityContext with default System authentication/user
body: <p>In my spring application, I would like that a <code>SecurityContext</code> always holds an <code>Authentication</code>. If it's not a regular <code>UsernamePasswordAuthenticationToken</code>, it will be a <code>PreAuthenticatedAuthenticationToken</code> describing the "system user." This has reasons within different system function which requires a user. To avoid a special treatment if there is no user context, I merely want to add the system context. IMHO, this has also to do with the single responsibility principle.</p>
  
  <p>To achieve this, I can simply implement my own <code>SecurityContextHolderStrategy</code> and set the it to the <code>SecurityContextHolder</code> with <code>SecurityContextHolder.setStrategyName(MyStrategyClassName);</code></p>
  
  <p><strong>Now to the problem:</strong></p>
  
  <p>The default <code>SecurityContextHolderStrategy</code> is the  <code>ThreadLocalSecurityContextHolderStrategy</code>. I'm happy with this strategy and how it works. The only thing which I would change is the <code>getContext()</code> method. </p>
  
  <pre><code>public SecurityContext getContext() {
      SecurityContext ctx = CONTEXT_HOLDER.get();
  
      if (ctx == null) {
          ctx = createEmptyContext();
          CONTEXT_HOLDER.set(ctx);
      }
      return ctx;
  }
  </code></pre>
  
  <p>to</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>This is <strong>not</strong> possible as the <code>ThreadLocalSecurityContextHolderStrategy</code> class is <strong>not <code>public</code></strong>. Of course I can simply copy paste the code of the <code>ThreadLocalSecurityContextHolderStrategy</code> into my own <code>SecurityContextHolderStrategy</code> and implement the <code>getContext()</code> method the way I want. But this gives me the feeling as I might be on the wrong path.</p>
  
  <p>How could I achieve a "system user" <code>Authentication</code> as default for a new <code>SecurityContext</code>?</p>
  
  <p><strong>Update</strong></p>
  
  <p>My approach above is apparently not a solution as it is extremely invasive, creates redundant code and needs special treatment within the web filter chain. But it should give an understanding of my goal. 
  I'm looking for a solution, which fits as seamless as possible to the native spring security implementation.
  My problem is that I'm quite fixed on the invasive approach. How can this solve nicely? I cannot imagine that I'm the first person with this requirement. Or is the whole concept altogether wrong?</p>