WebSocket的用户身份认证

关于Session认证的探索

使用环境

SpringBoot 2.x, Spring 4.x

碰到的问题

由于WebSocket是基于TCP的一种独立实现,跟HTTP没什么关系。在WebSocket进行权限验证时无法拿到Tomcat内置的session

解决方案

既然不能从Tomcat中拿到需要session,那倒可以在用户登陆时先将用户session用Map存储起来,后面便可以在WebSocket中利用Map拿到相应的用户信息。

首先需要一个用来存储Session的Map容器,使用了单例模式保证有唯一实例,并且使用Map存储了JSESSIONID以及相应的HttpSession

public class SessionContext {
    private static SessionContext instance;
    private Map<String, HttpSession> map;

    private SessionContext() {
        map = new HashMap<>();
    }

    public static SessionContext getInstance() {
        if (instance == null) {
            instance = new SessionContext();
        }
        return instance;
    }

    synchronized void AddSession(HttpSession session) {
        if (session != null) {
            map.put(session.getId(), session);
        }
    }

    synchronized void DelSession(HttpSession session) {
        if (session != null) {
            map.remove(session.getId());
        }
    }

    public synchronized HttpSession getSession(String session_id) {
        if (session_id == null) return null;
        return map.get(session_id);
    }
}

为此需要,一个HttpSession监听器,监听Session的创建与销毁,并相应新增与删除Map集合中的键值对:

@WebListener
public class SessionListener implements HttpSessionListener {
    private SessionContext sessionContext = SessionContext.getInstance();

    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        log.info("创建Session");
        sessionContext.AddSession(httpSessionEvent.getSession());
    }

    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        sessionContext.DelSession(session);
    }
}

最后使用一个WebSocket拦截器,在连接之前进行用户身份的认证:

@Service
public class WebSocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                                   WebSocketHandler webSocketHandler, Map<String, Object> map) {
        
        log.info("webSocket握手请求...");

        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
            
            // 得到放在url后面的JSESSIONID
            String jSessionId = servletRequest.getServletRequest().getParameter("JSESSIONID");
            
            // 得到Map单例类实例
            SessionContext sessionContext = SessionContext.getInstance();
            // 得到用户session
            HttpSession httpSession = sessionContext.getSession(jSessionId);
            if (null != httpSession) {
                User user = (User) httpSession.getAttribute("user");
                if (null != user) {
                    // 通过
                    return true;
                }
            }
            
            // 拦截该连接
            return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler, Exception e) {
        log.info("webSocket握手结束...");
    }
}
请求header认证

若系统使用spring-session-redis进行Session的管理,可以使用请求header验证

配置HttpSessionConfig配置类:

@EnableRedisHttpSession(maxInactiveIntervalInSeconds= 1800)
public class HttpSessionConfig {
    @Bean
    public HeaderHttpSessionIdResolver httpSessionStrategy() {
        return new HeaderHttpSessionIdResolver("x-auth-token");
    }
}

此时可以发现登陆后返回的 header头部信息中含有x-auth-token参数,将该参数作为请求头文件即可使用session验证。同时该参数为session的id,可以根据redis的spring:session:sessions:+ sessionId拿去到相应的用户信息。

目前使用存在许多问题,包括每次发起请求服务器都会存储一个session并返回该session的Id,长此以往,redis将被一堆无用session填满。因此还没有找到一个适合的能够替代上面的解决方法,如果有好的方法欢迎留言。
以清楚原因:有想了解的点击跳转

拓展

SpringSession

利用Spring Session可以使得Session脱离Tomcat本地的限制,在分布式系统上可以很轻松地实现Session共享。

JSON Web Token

除了Session认证,JWT认证也不失为一个好方案,能够实现单点登录以及用户认证。

服务器认证以后,生成一个 JSON 对象,发回给用户,就像下面这样。

{
    "userId":1,
    "userPhone":1213213123
}

用户与服务器通信时,服务器根据JSON对象判断用户身份,同时为了防止用户用户篡改数据,利用加密算法生成签名,并附在一个字符串中并返回给用户。

利用JWT认证服务器可以不用存储Session数据,减少了内存的负担。但还是存在着许多问题,包括:

  • 敏感信息不能使用JWT传递
  • JWT是无状态的导致服务器无法及时注销或修改用户信息,一旦JWT签发了,除非服务器部署额外的逻辑,否则在到期之前就会始终有效。
  • JWT续签问题
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值