Sending message to specific user using spring

2019-09-11 01:52发布

问题:

My Goal - To send message to single user if possible without using spring security

I want to input a username from user and set it as username in spring security so that I can use method convertAndSendToUser. I searched on the net and found two approaches

  1. Using DefaultHandshakeHandler to set username but this way I am unable to retrieve user input from the page and use it in determineUser method
  2. I have tried using following piece of code

    Authentication request = new UsernamePasswordAuthenticationToken("xyz", null); SecurityContextHolder.getContext().setAuthentication(request);

    But it is not working as it is just changing the username for that method and then it resets the username. If possible is there any approach with which I can send message to single user without using spring security. Thanks in advance

P.S. I am a newbee.

回答1:

You can use your first approach to set the Username. First you need add the interceptor to your StompEndpointRegistry class and after that you can determine User from the attributes Map and return the Principal.

Below is the Code:

HttpSessionHandshakeInterceptor is Used for Intercepting the Http attributes and provide them in the DefaultHandshakeHandler class

@Configuration
@EnableWebSocketMessageBroker
@EnableWebMvc
@Controller
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {


@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic");
    config.setApplicationDestinationPrefixes("/app","/user");

}

public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/chat")
     //Method .addInterceptors for enabling interceptor
    .addInterceptors(new HttpSessionHandshakeInterceptor())
    .setHandshakeHandler(new MyHandler())
    .withSockJS();
}

class MyHandler extends DefaultHandshakeHandler{


    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
            Map<String, Object> attributes) {

//Get the Username object which you have saved as session objects

    String name  = (String)attributes.get("name");

 //Return the User
    return new UsernamePasswordAuthenticationToken(name, null);
    }
  }

}