How to connect to a socket after logging in - JWT

I am using socketio-jwt for socket authentication.

On server:

socketio.use(require('socketio-jwt').authorize({ secret: config.secrets.session, handshake: true })); 

On the client:

 var ioSocket = io('', { query: 'token=' + Auth.getToken(), path: '/socket.io-client' }); 

My problem is that if the client connects to the server, authentication fails and the connection to the socket is not established. Now, if the user logs in, the connection to the socket is not established.

I am trying to ensure that if the user logs in, the connection is established.

My only idea is to reload the page with $window.location.href = '/'; after logging in. But that doesn't seem to be the right way.

Another option is to save a socket trying to (re) connect with a timeout. But its a bad option, as my application allows users without login.

How to properly call a socket connection?

+6
source share
2 answers

Here is the solution to your problem

Firstly, on your server side you can implement and bind user credentials to token as shown below.

 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. 

On the server side of socket.io you can do the following

  //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 

When client sends a valid jwt connection, it starts

A simple client-side file contains the following 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 )}) 
0
source
 var socket = require('socket.io'); var express = require('express'); var http = require('http'); var app = express(); var server = http.createServer(app); var io = socket.listen(server); io.on('connection', function (client) { // here server side code }) server.listen(5000); on client side include node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js socket = io.connect(site_url + ":5000", { reconnect: !0 }); 
0
source

All Articles