dongyukun
8 天以前 a23e66f179586eeffc55d116f5a3bb53eab9cb09
提交 | 用户 | 时间
e7c126 1 package com.iailab.framework.websocket.core.security;
H 2
3 import com.iailab.framework.security.core.LoginUser;
4 import com.iailab.framework.security.core.filter.TokenAuthenticationFilter;
5 import com.iailab.framework.security.core.util.SecurityFrameworkUtils;
6 import com.iailab.framework.websocket.core.util.WebSocketFrameworkUtils;
7 import org.springframework.http.server.ServerHttpRequest;
8 import org.springframework.http.server.ServerHttpResponse;
9 import org.springframework.web.socket.WebSocketHandler;
10 import org.springframework.web.socket.WebSocketSession;
11 import org.springframework.web.socket.server.HandshakeInterceptor;
12
13 import java.util.Map;
14
15 /**
16  * 登录用户的 {@link HandshakeInterceptor} 实现类
17  *
18  * 流程如下:
19  * 1. 前端连接 websocket 时,会通过拼接 ?token={token} 到 ws:// 连接后,这样它可以被 {@link TokenAuthenticationFilter} 所认证通过
20  * 2. {@link LoginUserHandshakeInterceptor} 负责把 {@link LoginUser} 添加到 {@link WebSocketSession} 中
21  *
22  * @author iailab
23  */
24 public class LoginUserHandshakeInterceptor implements HandshakeInterceptor {
25
26     @Override
27     public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
28                                    WebSocketHandler wsHandler, Map<String, Object> attributes) {
29         LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
30         if (loginUser != null) {
31             WebSocketFrameworkUtils.setLoginUser(loginUser, attributes);
32         }
33         return true;
34     }
35
36     @Override
37     public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
38                                WebSocketHandler wsHandler, Exception exception) {
39         // do nothing
40     }
41
42 }