使用spring向特定用户发送消息
我的目标 - 在不使用 Spring Security 的情况下尽可能向单个用户发送消息
My Goal - To send message to single user if possible without using spring security
我想从用户输入用户名并将其设置为 Spring Security 中的用户名,以便我可以使用方法 convertAndSendToUser
.我在网上搜索,找到了两种方法
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
- 使用
DefaultHandshakeHandler
设置用户名,但这样我无法从页面检索用户输入并在determineUser
方法中使用它 我尝试使用以下代码
- Using
DefaultHandshakeHandler
to set username but this way I am unable to retrieve user input from the page and use it indetermineUser
method I have tried using following piece of code
Authentication request = new UsernamePasswordAuthenticationToken("xyz", null);SecurityContextHolder.getContext().setAuthentication(request);
但它不起作用,因为它只是更改该方法的用户名,然后重置用户名.如果可能的话,是否有任何方法可以在不使用 spring 安全性的情况下向单个用户发送消息.提前致谢
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
附言我是新手.
您可以使用第一种方法来设置用户名.首先,您需要将拦截器添加到您的 StompEndpointRegistry 类中,然后您可以从 属性 映射中确定用户并返回 主体.
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.
代码如下:
HttpSessionHandshakeInterceptor 用于拦截 Http 属性并在 DefaultHandshakeHandler 类中提供它们
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);
}
}
}