Spring WebSocket在 Config 中访问 Cookie
2024-01-21 02:13:55
230次阅读
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
- 0回答
- 1粉丝
- 0关注
相关话题
- websocket自动断开连接
- Nginx配置WebSocket负载均衡
- Spring boot打包后从类路径目录中获取资源列表
- 解决spring mvc 返回json对象时ie浏览器访问会出现下载文件弹出框
- spring配置文件中bean的属性name与id的区别
- seaweedfs在windows上使用
- seaweedfs在windows上部署参考
- SeaweedFS在linux上配置使用
- Springboot中WebMvcConfigurer中可配置项
- Spring下载地址
- Spring常用注解
- Markdown 中忽略 HTML 标签
- nginx禁止访问文件或目录的配置方法及location指令的uri匹配规则
- Spring MVC 文件下载
- HTTP Header中不能传输中文