gpt4 book ai didi

spring-websocket - Spring WebSocket。在 Config 中访问 Cookie

转载 作者:行者123 更新时间:2023-12-01 07:24:32 25 4
gpt4 key购买 nike

我正在尝试使用 STOMP、OAuth 2 和 SockJS 通过 Spring 配置 WebSocket。
新规范 tells us 如何使用拦截器实现它。
情况是:如果用户通过身份验证,CONNECT请求的Native header中有一个Bearer Token,通过Token设置principal没有问题。
但我的任务是将 BrowserToken 用于未经授权的用户(保存在 Cookies 中)。我怎样才能从请求中得到它?

最佳答案

我找到了一个解决方案:

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

关于spring-websocket - Spring WebSocket。在 Config 中访问 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41367105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com