Manually setting authenticated user on a websocket session using spring security

4.7k views Asked by At

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.

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.

The question is: how do I authenticate the user of the websocket session?

To make a similar thing using a normal MVC web application I would use a code similar to this:

@MessageMapping("/auth")
public Object auth() {
  List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_TEST");
  SecurityContextHolder.getContext().setAuthentication(new PreAuthenticatedAuthenticationToken(myname, "dummy", authorities));
}

but this seems not work in a websocket environment because when the user a method like this:

@MessageMapping("/myendpoint")
public Object myEndpoint(Param params, Principal principal) {...}

I get the error:

org.springframework.messaging.simp.annotation.support.MissingSessionUserException: No "user" header in message

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?

0

There are 0 answers