简体   繁体   中英

How to secure JWT token and refresh token in nodejs/angular

i am new in node js. I am building a simple notes taking app and wanted to use JWT tokens for authentication and to secure my API's. On research i came to know that i need to create two tokens:

  1. access token (short expire time like 10 minutes)
  2. refresh token (longer expire time 30 days)

My config file

"secret": "*************",
"refreshTokenSecret": "*************",
"port": 5000,
"tokenLife": 900,
"refreshTokenLife": 86400

Code for middleware

const jwt = require('jsonwebtoken')
const config = require('./config')

module.exports = (req,res,next) => {
  const token = req.body.token || req.query.token || req.headers['x-access-token']
  // decode token
  if (token) {
    // verifies secret and checks exp
    jwt.verify(token, config.secret, function(err, decoded) {
        if (err) {
            return res.status(401).json({"error": true, "message": 'Unauthorized access.' });
        }
      req.decoded = decoded;
      next();
    });
  } else {
    // if there is no token
    // return an error
    return res.status(403).send({
        "error": true,
        "message": 'No token provided.'
    });
  }
}

Here is the response

在此处输入图像描述

access token can be saved in local storage. but articles said save refresh token as http-only cookie. i need the answer of following points (Keeping in mind that i am just a beginner):

  1. How to store refresh token as http-only cookie (any node-js code example would be a great help)?
  2. How to secure it on client side and should I save refresh token to database?
  3. Is there any other better solution to secure my API's?

You can use an http-only cookie using the following:

public authenticateUser(user: User, res: Response) {
        const authJwtToken = this.generateJWT({
            email: user.email,
            uuid: user.uuid
        });

        const cookieOptions = {
            maxAge: 3600000,
            secure: true,
            httpOnly: true
        };

        res.cookie('access_token', authJwtToken, cookieOptions);
    }
// you can then res.send({...}) or wtv

Not that there is nothing from preventing you to store more than one cookie so I can't see a reason why not storing both of them in the same manner.

Now whether you will store it on the database depends on what you want to achieve. Generally it is not required but note that in that case the server cannot in any way invalidate a single JWT. (You could in theory change the signing key but this would invalidate all of them).

In case you want to be able to achieve functionality such as 'log me out of all devices' you would need to store the JWTs issued for each user in a database (preferably an in-memory one such as Redis or Memcached) and do a second check with the extra information on whether they have been invalidated or not - even though such functionality is typically achieved using sessions instead of JWT

See this example how i secured my getByRefId api in nodjs:

In routes file:

router.get("/refId/:refId", helper.auth, groupController.getByRefId);

helper.auth is   function  :

auth: (req, res, next) => {
    var token = req.body.token || req.headers['authorization'] || req.headers['Authorization'];

    if (token.startsWith('Bearer ')) {
        // Remove Bearer from string
        token = token.slice(7, token.length).trimLeft();
    }

    if (token) {
        jwt.verify(token, 'MY_SECRET', function (err, decoded) {
            if (err) {
                console.error('JWT Verification Error', err);
                return res.status(403).send(err);
            } else {
                req.payload = decoded;
                return next();
            }
        });
    } else {
        res.status(403).send('Token not provided');
    }
}

This use jwt = require('jsonwebtoken') library you can install it in nodejs project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM