1

当我试图保护用户 API 时;我总是 401 未经授权。我尝试了不同的变体来定义策略;但没有运气。在使用 Secret 和 RS256 算法签署令牌时,我一直在使用 JWTStrategy 和 jwtwebtoken

Passport.js

// import * as module from 'module';
const
  User = require('../models/user'),
  JwtStrategy = require('passport-jwt').Strategy,
  ExtractJwt = require('passport-jwt').ExtractJwt,
  config = require('./appconfig');

// Setting JWT strategy options
const jwtOptions = {
  // Telling Passport to check authorization headers for JWT
  jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
  // Telling Passport where to find the secret
  secretOrKey: config.jwtSecret,
  algorithms:['RS256']
  // TO-DO: Add issuer and audience checks
};

console.log(config.jwtSecret);
module.exports = function(passport) {
  passport.use(new JwtStrategy(jwtOptions, function(jwt_payload, done) {
    console.log(jwt_payload);
    User.findOne({id: jwt_payload.sub}, function(err, user) {
      if (err) {
          return done(err, false);
      }
      if (user) {
          return done(null, user);
      } else {
          return done(null, false);
          // or you could create a new account
      }
    });
  }));
};

索引.Route.js

const express = require('express');
const userRoutes = require('./user.route');
const authRoutes = require('./auth.route');
// const postRoutes = require('./post.route');
const passport = require('passport');


passport.initialize();
var jwt = require('../config/passport')(passport);

const router = express.Router(); // eslint-disable-line new-cap

/** GET /health-check - Check service health */
router.get('/health-check', (req, res) =>
  res.send('OK')
);

// mount user routes at /users
router.use('/users', passport.authenticate('jwt', { session: false }), userRoutes);

// mount auth routes at /auth
router.use('/auth', authRoutes);

// router.use('/posts', postRoutes);

module.exports =  router;

使用邮递员:标头:身份验证:JWT 令牌

本地主机:4040/api/用户

4

1 回答 1

1

您是否在标题部分配置了邮递员?你能显示 JwtStrategy 代码吗?

于 2018-05-23T07:08:11.510 回答