使用spring向特定用户发送消息 [英] Sending message to specific user using spring

查看:41
本文介绍了使用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

  1. 使用 DefaultHandshakeHandler 设置用户名,但这样我无法从页面检索用户输入并在 determineUser 方法中使用它
  2. 我尝试使用以下代码

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

但它不起作用,因为它只是更改该方法的用户名,然后重置用户名.如果可能的话,是否有任何方法可以在不使用 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);
    }
  }

}

这篇关于使用spring向特定用户发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆