M
M
MR.TOSTER Gipard Valerievich2016-08-12 12:41:01
Node.js
MR.TOSTER Gipard Valerievich, 2016-08-12 12:41:01

Socket.io authorization with own generated token, how?

Let's assume that at login the user is given a cookie - a token.
How to make authorization on socket.io based on this? (node)
During authorization, the token will be checked whether it is in the database, and if so, give it.
PS: I found several manuls, but they were all written 3 years or more ago. And they are all spelled differently, which is misleading.
I hope that you already have a snippet that you use in your projects and that could be useful to me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Matvey Safronov, 2016-08-12
@zoceb

The token can store any information in encrypted form. In case of successful authorization, place a unique value in the token, on the basis of which you can later obtain user data, organizing a session based on it. The simplest case is to store a unique user id in the token. You can implement it using the "jsonwebtoken" plugin.
Let's create a separate "secure.js" module for token generation/decryption:

let Secure = function() {
  
  const SECRET_PHRASE = 'secret';
  
  let jwt = require('jsonwebtoken');

  let getSecretPhrase = () => {
    return SECRET_PHRASE;
  };
  
  let generateToken = (userEntityId) => {
    return jwt.sign({ 'entity_id' : userEntityId }, SECRET_PHRASE);
  };
  
  let verifyToken = (token) => {
    return jwt.verify(token, SECRET_PHRASE);
  };
  
  return {
    getSecretPhrase : getSecretPhrase,
    generateToken : generateToken,
    verifyToken : verifyToken
  }
  
};

module.exports = new Secure();

When authorizing by login and password, we will generate a token for the client in case of success, placing a unique user _id in it:
/* обращаемся к базе, находим пользователя по логину и паролю (userData) */
let secure = require('./secure.js');
var token = { 'token' : secure.generateToken(userData._id) };

On the server-socket side, we get an object of this token:
Let's decrypt and extract the _id of the user from the authorization:
let secure = require('./secure.js');
var uid;
try {
uid = secure.verifyToken(token).entity_id;
} catch(e) {
//
}

And by this uid we find the data in the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question