title: Manually setting authenticated user on a websocket session using spring security
body: <p>I'm developing a Spring boot application using STOMP messaging over a websocket implementing an RPC pattern which exposes public (i.e.: without any need to be authenticated) and private methods.</p>
  
  <p>Two public methods exists to register and authenticate the user, so I need to manually (programmatically) handle the user login, method accessed via a custom @MessageMapping operation.</p>
  
  <p>The question is: how do I authenticate the user of the websocket session?</p>
  
  <p>To make a similar thing using a normal MVC web application I would use a code similar to this:</p>
  
  <pre><code>@MessageMapping("/auth")
  public Object auth() {
    List&lt;GrantedAuthority&gt; authorities = AuthorityUtils.createAuthorityList("ROLE_TEST");
    SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken(myname, "dummy", authorities));
  }
  </code></pre>
  
  <p>but this seems not work in a websocket environment because when the user a method like this:</p>
  
  <pre><code>@MessageMapping("/myendpoint")
  public Object myEndpoint(Param params, Principal principal) {...}
  </code></pre>
  
  <p>I get the error:</p>
  
  <pre><code>org.springframework.messaging.simp.annotation.support.MissingSessionUserException: No "user" header in message
  </code></pre>
  
  <p>So the question is: how do I manually authenticate the user in the auth() method so that in myEndpoint() the Principal parameter is correctly resolved?</p>