【问题标题】: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。
类似这样的:
1.在客户端,通过Socket.io创建socket对象
const socket = io(
`YOUR_URL`,
{
"transports": ["websocket", "polling", "flashsocket"],
"query": { "authorization": `Bearer ${token}` } // <= token in here
}
);
- 创建拦截器,然后在套接字控制器中使用它
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) {
// ...
}
}