如何使用passport-jwt登录后解码令牌

Sau*_*rma 3 token node.js passport.js

我正在使用带有passport-jwt的登录用户ID编码令牌,如下所示:

var JwtStrategy   =require('passport-jwt').Strategy;
ExtractJwt = require('passport-jwt').ExtractJwt;
var User          =require('../app/models/usermodel');
var config        =require('../config/database');

module.exports=function(passport){
    var opts = {}; 
    opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    User.findOne({id: jwt_payload.id}, function(err, user) {
          if (err) {
              return done(err, false);
          }
          if (user) {
              done(null, user);
          } else {
              done(null, false);
          }
      });
  }));
};
Run Code Online (Sandbox Code Playgroud)

和登录路由API:

apiRoutes.put('/login', function(req, res, next){
  User.findOne({email:req.body.email}, function(err, user){
    bcrypt.compare(req.body.password, user.password, function(err, result){
       if(result){
        var token=jwt.encode(user, config.secret);
        return res.json({token:token}); 
      }else{
        return res.json("Incorrect Email and Password")
      }
    })
  })
});
Run Code Online (Sandbox Code Playgroud)

现在我想在仪表板页面中获取登录用户的信息。为此,我正在尝试解码令牌并尝试通过在仪表板 API 路由中添加身份验证来获取用户的所有信息,如下所示:

apiRoutes.get('/dashboard', passport.authenticate('jwt', { session: false}), function(req, res) {
  console.log('User info: ' + req.user._id + '.');
  });
Run Code Online (Sandbox Code Playgroud)

上面的代码是我在解码令牌的教程中找到的。所以,当我点击这个/api/dashboardurl 时,它在浏览器控制台中显示错误。

GET http://localhost:3000/api/dashboard 401 (Unauthorized)
Run Code Online (Sandbox Code Playgroud)

我不知道如何解码令牌并获取用户信息。请帮我解决这个问题。

帮助表示赞赏。谢谢

Kas*_*ami 5

像这样将令牌传递给 jwt-decode

安装jwt-decode

npm i jwt-decode
Run Code Online (Sandbox Code Playgroud)

您可以非常轻松地使用它:

import * as jwtDecode from 'jwt-decode';

const payload = jwtDecode(token);
Run Code Online (Sandbox Code Playgroud)

例如我在nestjs中间件中使用了这个:

import { Injectable, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import { Request, Response } from 'express';
import { UserType } from 'src/users/enums/user.enum';
import * as jwtDecode from 'jwt-decode';

@Injectable()
export class ErrorIfNotUser implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    const token = req.headers.authorization.slice(7);
    const payload = jwtDecode(token);

    if (payload.type !== UserType.USER) {
      throw new UnauthorizedException(
        'sorry! just type user access to this route',
      );
    }

    next();
  }
}
Run Code Online (Sandbox Code Playgroud)

npm 中的 jwt-decode:https ://www.npmjs.com/package/jwt-decode