简体   繁体   English

Spring Boot 原始 WebSocket 设置主体

[英]Spring Boot Raw WebSocket Set Principal

I want to develop notification sender in real time with Spring Boot but I can't use Stomp and sockjs, so I need implement raw WebSocket but I can't find out how to set Principal in WebSocket connection beacuse I want to Authenticate with JWT token.我想用 Spring Boot 实时开发通知发送器,但我不能使用 Stomp 和 sockjs,所以我需要实现原始 WebSocket,但我无法找到如何在 WebSocket 连接中设置 Principal 因为我想使用 JWT 令牌进行身份验证. So, where or how can I set principal.那么,我在哪里或如何设置主体。 I'am using these;我正在使用这些;

WebSocketConfig.java : WebSocketConfig.java :

@EnableWebSocket
@Configuration
public class WebSocketConfig implements WebSocketConfigurer {

  @Autowired
  WebSocketNotificationSenderService senderService;

  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry
                                              webSocketHandlerRegistry) {

     webSocketHandlerRegistry.addHandler(createHandler(),
            "/handler").addInterceptors(new HttpSessionHandshakeInterceptor()
     {
        @Override
        public void afterHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response, WebSocketHandler wsHandler,
                                   @Nullable Exception ex) {

            super.afterHandshake(request, response, wsHandler, ex);

        }

        @Override
        public boolean beforeHandshake(ServerHttpRequest request,
                                       ServerHttpResponse response, WebSocketHandler wsHandler,
                                       Map<String, Object> attributes) throws Exception {

            return super.beforeHandshake(request, response,
                    wsHandler, attributes)
        }

    });
}

@Bean
public WebSocketHandler createHandler() {

    return new MyHandler(senderService);

}
}

MyHandler.java : MyHandler.java :

@Component
public class MyHandler extends TextWebSocketHandler {

WebSocketNotificationSenderService senderService;

public MyHandler(WebSocketNotificationSenderService senderService){
    this.senderService = senderService;
}

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    senderService.addToSession(session);
}
}

WebSocketNotificationSenderService.java : WebSocketNotificationSenderService.java :

@Service
public class WebSocketNotificationSenderService implements 
IWebSocketSenderService<WrapperWsNotification> {

private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
private ObjectMapper mapper = new ObjectMapper();

public void addToSession(WebSocketSession session) {
    sessions.add(session);
}

@Override
public void convertAndSend(WrapperWsNotification payload) throws JsonProcessingException {
    String payloadString = mapper.writeValueAsString(payload);
    sessions.stream().forEach(session -> {
        try {
            session.sendMessage(new TextMessage(payloadString));
        } catch (IOException e) {
            e.printStackTrace();
        }

    });
}

@Override
public void convertAndSendToUser(String user, WrapperWsNotification payload) throws 
  JsonProcessingException {
    String payloadString = mapper.writeValueAsString(payload);
    sessions.forEach(session -> {
        if (session.getPrincipal().getName().equals(user)) {
            try {
                session.sendMessage(new TextMessage(payloadString));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}
}

My Notification Sender to websocket;我的通知发件人到 websocket;

@Component
public class NotificationConsumer {

@Autowired
WebSocketNotificationSenderService webSocket;

private Logger logger = LoggerFactory.getLogger(NotificationConsumer.class);

public void onReceiveNotification(String object) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    WrapperWsNotification wrapperWsNotification= objectMapper.readValue(object, WrapperWsNotification.class);
    logger.info("User where coming from redis " + wrapperWsNotification.getUser().getUsername());
    webSocket.convertAndSendToUser(wrapperWsNotification.getUser().getUsername(), wrapperWsNotification);
}


}

我找到了解决方案并添加了一个示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM