Jsonwebtoken and use of express-jwt

User rights verification is nodeJs, token generation and verification tools, stepped pit recording ~~~ - jsonwebtoken and express-jwt

Steps for usage:

First, download

npm install jsonwebtoken --save
npm install express-jwt --save

Second, the token generates token authentication and

In user.js file

const jwt = require('jsonwebtoken');
//秘钥
var signkey = 'mes_qdhd_mobile';
//生成token
const setToken = function (username) {
    return new Promise((resolve, reject) => {
        const token = jwt.sign({
            username: username
        }, signkey, { expiresIn:  60 * 60 * 24 * 3 });
        // let info = jwt.verify(token.split(' ')[1], signkey)
        // console.log(info);
        console.log('token',token);
        resolve(token);
    })
}
//验证token
const verToken = function (token) {
    return new Promise((resolve, reject) => {
        var info = jwt.verify(token, signkey ,(error, decoded) => {
            if (error) {
              console.log(error.message)
              return
            }
            console.log(decoded)
          });
        resolve(info);
    })
}

Third, access to parse token, to determine whether or not effectively

In the app.js

const jwt = require('jsonwebtoken');
var user = require('./user.js');
// parse token for user information 
app.use (function (REQ, RES, Next) {
   var token = req.headers [ ' Authorization ' ]; IF (token == undefined) {
         return Next (); 
    } the else { 
     User. verToken (token) .then ((Data) => { 
            req.data = Data;
             return Next (); 
        }). the catch ((error) => { 
          the console.log (error); 
            return Next (); 
        }) 
    } 
}); 

// verification token has expired and no verification provisions which routes
app.use (expressJwt ({ 
  Secret: ' mes_qdhd_mobile ' 
.}) The unless ({ 
  path: [ ' / ' , ' / User / Login ' ] // In addition to this address, other URL requires authentication 
}));

Fourth, tips

// error handler
app.use(function (err, req, res, next) {
  console.log(err);
  if (err.name === 'UnauthorizedError') {
    console.error(req.path + ',无效token');
    res.json({
      message: 'token过期,请重新登录',
      code: 400
    })
    return
  }
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

Cai pit record:

Has been in the newspaper format .... Bearer [token] ....

Finally discovered, get in front of the token is a Bearer of, when passing the front of the head, before the token plus "Bearer", will be successful! !

Guess you like

Origin www.cnblogs.com/blog-zy/p/11840964.html