gpt4 book ai didi

node.js - SocketCluster 中间件握手 promise

转载 作者:行者123 更新时间:2023-12-04 18:35:28 25 4
gpt4 key购买 nike

我正在构建一个同时服务于 http 和 ws 的应用程序。用户首先通过 HTTP 登录到 Laravel 服务器。这将返回一个用于允许通过 WS 登录的 JWT。

Ihv 添加了一个 MIDDLEWARE_HANDSHAKE 来获取 token 并向 Laravel 服务器发出请求以询问该 token 是否有效以及用户是否可以访问 WS(并非每个登录的用户都被允许访问 WS);

客户端代码:

var options = {
host: '127.0.0.1:3000',
query: {
source: 'web',
token: '',
}
};

var socket;

$.post('http://127.0.0.1:8000/authenticate', {
email: 'chadd01@example.org',
password: '1234'
}, function(data, textStatus, xhr) {
options.query.token = data.token;

//ALL PERFECT UNTILL HERE

// Initiate the connection to the ws server
socket = socketCluster.connect(options)
.on('connect', function(data) {
console.log('CONNECTED', data);
})
.on('error', function(data) {
console.log('ERROR', data.message);
});
});

SocketCluster 服务器代码:

scServer.addMiddleware(scServer.MIDDLEWARE_HANDSHAKE, function(request, next) {
var query = url.parse(request.url, true).query;
switch (query.source) {
case 'web':
case 'mobile-app':
validateUser(query)
.then((response) => {
next(); //Allowed
})
.catch((code) => {
next(code); //Blocked with StatusCode
});
break;

default:
next(true, 'NOT_AUTHORIZED'); // Block
break;
}
});

validateUser = (credentials = {}) => {
return new Promise((resolve, reject) => {
request({ url: API + 'webSocket/users/' + credentials.token, method: 'GET' }, (error, response, body) => {
if (response.statusCode === 200) {
resolve(body);
}
reject(response.statusCode);
});
});

};

在像这样实现这个中间件时,即使验证成功,我也会不断从 ws 服务器获得此响应:

WebSocket connection to 'ws://127.0.0.1:3000/socketcluster/?source=web&token=<_TOKEN_>' failed: Connection closed before receiving a handshake response

(index):149 ERROR Socket hung up

但是,如果我像这样实现 HANDSHAKE_MIDDLEWARE:

scServer.addMiddleware(scServer.MIDDLEWARE_HANDSHAKE, function(request, next) {
var validUser = true;
if (validUser){
return next();
}
return next('NOT_A_VALID_USER');
});

一切顺利:

CONNECTED Object {id: "W067vqBc9Ii8MuIqAAAC", pingTimeout: 20000, isAuthenticated: true, authToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6I…xOTV9.E4bLPh4Vjk9ULvfhW6prjBbVt0vOD32k63L1vlDtGrU"}

所以问题似乎出在 Promise 回调中。

如果这不是正确的实现方式,有什么建议吗?

谢谢。

最佳答案

在 SocketCluster 上使用 JWT 的一个重要原因是处理登录和身份验证,您是否考虑过只使用 WS?

看看SocketCluster authentication .


您当前的 HTTP 代码如何检查登录数据,您可以对 WS 执行相同的操作并使用 socket.setAuthToken 设置 token (这是我在我的项目):

socket.setAuthToken({
email: credentials.email,
id: returnedData.id,
permission: returnedData.permission
});

然后您可以仍然使用 on/emit 向 WS 服务器发出请求,并检查它们是否已通过身份验证。这是我的 authCheck 函数的修改片段:

const token = socket.getAuthToken();

if (token && token.email) {
console.log('Token Valid, User is: ', token.email);
// user validated - continue with your code
} else {
console.log('Token Invalid, User not authenticated.');
// respond with error message to the user
}

关于node.js - SocketCluster 中间件握手 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42394884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com