【问题标题】:Authenticating Socket connection using JWT & Loopback 4使用 JWT 和 Loopback 4 验证 Socket 连接
【发布时间】:2020-05-03 08:20:45
【问题描述】:

我按照以下example 使用 LB4 和 Socket.io 构建了一个聊天应用程序,现在我需要使用 JWT 保护该应用程序。如何将以下reference 中提到的 JWT 策略集成为我的应用程序架构的一部分。有可能做这样的事情吗?

@ws.connect()
@authenticate('jwt')
  connect(socket: Socket) {
    console.log('Client connected: %s', this.socket.id);
    socket.join('room 1');
  }

【问题讨论】:

    标签: node.js typescript jwt loopback4


    【解决方案1】:

    对我来说,我使用Interceptors

    • 创建拦截器
    • 获取Handeshake 对象
    • 验证它

    类似这样的:

    1.在客户端,通过Socket.io创建socket对象

    const socket = io(
        `YOUR_URL`,
        {
            "transports": ["websocket", "polling", "flashsocket"],
            "query": { "authorization": `Bearer ${token}` } // <= token in here
        }
    );
    
    1. 创建拦截器,然后在套接字控制器中使用它
    export const SocketAuth = (): Interceptor => {
        return async (invocationCtx, next) => {
            const handshake: Handeshake = (invocationCtx.target as any).socket.handshake;
            // ...
        }
    }
    
    @ws('/chat')
    export class ChatController {
    
        @intercept(SocketAuth) // <= !!!!
        @ws.connect()
        async connect(socket: Socket) {
            // ...
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-15
      • 2017-08-16
      • 1970-01-01
      • 2020-09-04
      • 2020-06-19
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 2020-07-14
      相关资源
      最近更新 更多