Consulta about protecting apis and sessions in nodejs

0

My query is the following, I want to manage user sessions, that is to say an account, have c / u their own things, besides I want to protect my apis, finding out a little, I have seen that I can use jwt in nodejs along with sails for manage the sessions, I have also seen that with passport I can do it, now well, with respect to apis protection I have seen that it can be done with jwt.

-For those who have already worked with it, that other alternatives exist to manage sessions (I see that passport is discontinued) and according to their experience which they would choose for it, the same for the protection of apis.

    
asked by Kevin AB 23.09.2016 в 13:58
source

2 answers

1

To begin with, we should analyze the difference between a session and a token-based authentication system . JSON Web Token in this case.

The main difference is that JWT is stateless, that is, the server does not maintain the state of the client that communicates. On the other hand, the sessions do. That said, with the sessions the client authenticates only once (at least until the session expires) but the server needs to keep a minimum number of data from that client to maintain the session, on the other hand a token needs to be sent in each request to the server to authenticate / validate the request.

Think of the tokens as a disco bracelet, (which you have previously purchased), you can enter and leave the club as many times as you want, as long as you present the wristband at the entrance. At that point, it is the discoteca's responsibility to validate the bracelet, that is, to know if it is original, and you have not made it yourself. The disco does not care where you bought it, what is your name, or how many times you have entered and left, it only matters to be able to define if the bracelet (token) is true. All this in the context of clear authentication is.

For an API, using JSON Web Token has several advantages:

  • JWTs is self-contained , it carries information within itself, such as the user's information, for example. This can save you queries in the database.

  • They can be easily transferred everywhere. This is useful for example, if you have several microservices and want several clients (a web application and a mobile) to authenticate with the same token. It is enough that the servers involved know the salt that was used to apply the hash on the token.

  • As it is a standard, you can use it with different types of platforms and programming languages.

If you are using expressjs. A good starting point would be express-jwt .

    
answered by 23.09.2016 / 15:33
source
0
  

I see that passport is discontinued

Although there is still no official communication from Jared Hanson, you can deduce that yes by the date of the last commit (May 04).

Doing it with JWT is really very simple. You only need to generate a token and a middleware that checks the token for each API request.

Benefits

  • Scalability: the tokens are stored in the client but not in the backend as we would if we used sessions. In this way the application tends to make it more scalable.
  • Security: when not stored in cookies we have a security bonus against CSRF attacks, and we avoid manipulating the session.
  • Simplicity: when the token goes as a header in each request, we do not need to do anything other than check the integrity of the token.

Example

The first thing we must do is authenticate the user. For this we map a route in our API for it; let's say https://example.com/api/auth .

Packages required - express - body-parser - method-override - jsonwebtoken - bcrypt-nodejs

Authentication and token creation

import express from 'express';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt-nodejs';

const Router = express.Router();

Router.post('/auth', (request, response) => {
  User.findOne({ name: request.body.name })
    .then(user => {
      if(!user) {
        return response.json({
          success: false,
          message: 'Usuario inexistente'
        });
      }
      if(!bcrypt.compareSync(request.body.password, user.password)) {
        return response.json({
          success: false,
          message: 'Contraseña incorrecta'
        });
      }
      const token = jwt.sign(user, app.get('phrase'), {
        expiresInMinutes: 720 // 12 horas
      });

      return response.json({
        success: true,
        message: 'Usuario logueado',
        token
      });
    });
});

export default Router;

Middleware

Next, we have to write the middleware to check the token on each request.

import express from 'express';
import jwt from 'jsonwebtoken';

const Router = express.Router();

Router.use((request, response, next) => {
  const token = req.body.token || req.query.token || req.headers['x-access-token'];
  if(token) {
    jwt.verify(token, app.get('phrase'), (err, decoded) => {
      if(err) {
        return response.json({
          success: false,
          message: 'Token inválido. ¿Intentas bypassearme? >:|'
        });
      }
      request.decoded = decoded;
      next();
    })
  } else {
    return response.json({
      success: false,
      message: 'No hay un token asociado a esta petición'
    });
  }
});
export default Router;

Finally you associate that middleware with the API url:

app.use('/api', AuthMiddleware);
    
answered by 23.09.2016 в 15:06