Sending message to specific user using spring

扶醉桌前 提交于 2019-12-12 02:39:22

问题


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);
    }
  }

}


来源:https://stackoverflow.com/questions/39333910/sending-message-to-specific-user-using-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!