Ste*_*fan 7 sockets node.js socket.io jwt
我正在使用socketio-jwt来验证套接字.
在服务器上:
socketio.use(require('socketio-jwt').authorize({
secret: config.secrets.session,
handshake: true
}));
Run Code Online (Sandbox Code Playgroud)
在客户端:
var ioSocket = io('', {
query: 'token=' + Auth.getToken(),
path: '/socket.io-client'
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果客户端连接到服务器,则身份验证失败,并且不会建立与套接字的连接.现在,如果用户登录系统,则与套接字的连接仍未建立.
我试图实现的是,如果用户登录系统,则建立连接.
到目前为止,我唯一的想法是$window.location.href = '/';在登录后重新加载页面.但似乎不是正确的方式.
另一个选择是保持套接字尝试(重新)连接超时.但它是一个糟糕的选择,因为我的应用程序允许用户无需登录.
如何正确触发套接字连接?
这是您问题的解决方案
首先,在服务器端,您可以实现用户凭据并将其绑定到 a,token如下所示。
var jwt = require('jsonwebtoken');
app.post('/loginpage',function(req,res){
//validate the user here
});
//generate the token of the user based upon the credentials
var server = //create the http server here.
Run Code Online (Sandbox Code Playgroud)
在socket.io服务器端你可以执行以下操作
//require socket.io
var xxx = socketIo.listen //to the server
xxx.set('auth',socketIojwtauthorize({
secret: config.secrets.session,
handshake: true
}));
xxx.sockets //here connection on or off by setting up promise
//server listen to localhost and port of your choice
Run Code Online (Sandbox Code Playgroud)
当client发送有效jwt连接时被触发
简单的客户端文件将包含以下内容modules
//function connectsocket(token){
//connect(
//and query the token );
}
//socket.on('connect',function(){
//generate the success message here
}).on('disconnect',function(){ //your choice })
//rendering the routes with the server side
$.post('/loginroute',{
//user credentials passes here
}).done(function(bind){ connect_socket( bind.token )})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
929 次 |
| 最近记录: |