Spring WebSocket在 Config 中访问 Cookie

2024-01-21 02:13:55
57次阅读
0个评论

Spring 配置 WebSocket,使用 STOMP、OAuth 2 和 SockJS 方案。


在WebSocket 拦截器 CONNECT 请求的 Native 标头中有一个 Bearer Token,获取 Token 方法。


@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/websocket/tracker")
        .withSockJS()
        .setInterceptors(httpSessionHandshakeInterceptor());
}
@Bean
public HandshakeInterceptor httpSessionHandshakeInterceptor() {
    return new HandshakeInterceptor() {
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
            if (request instanceof ServletServerHttpRequest) {
                ServletServerHttpRequest servletServerRequest = (ServletServerHttpRequest) request;
                HttpServletRequest servletRequest = servletServerRequest.getServletRequest();
                Cookie token = WebUtils.getCookie(servletRequest, "key");
                attributes.put("token", token.getValue());
            }
            return true;
        }
        @Override
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        }
    };
}


@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
    registration.setInterceptors(new ChannelInterceptorAdapter() {
        @Override
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            StompHeaderAccessor accessor =
                MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
            if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                Map<String, Object> sessionAttributes = accessor.getSessionAttributes();
                List<String> authorization = accessor.getNativeHeader("Authorization");
                Principal user = ... ; // get Principal using authentication / browser token
                accessor.setUser(user);
            }

            return message;
        }
    });
}

收藏00

登录 后评论。没有帐号? 注册 一个。