护照-jwt sequelize 401 总是

Posted

技术标签:

【中文标题】护照-jwt sequelize 401 总是【英文标题】:passport-jwt sequelize 401 always 【发布时间】:2018-11-02 00:56:25 【问题描述】:

当我试图保护用户 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
      
    );
  ));
;

Index.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 令牌

localhost:4040/api/用户

【问题讨论】:

【参考方案1】:

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

【讨论】:

可以查看上面代码中的Strategy。 Passport.js

以上是关于护照-jwt sequelize 401 总是的主要内容,如果未能解决你的问题,请参考以下文章

护照-jwt 总是返回“未经授权” - 401

护照-jwt 401 未经授权

Laravel 护照 oauth 路线总是返回 401 未经授权

带有护照 jwt 的非对称密钥。验证总是返回 Unauthorized

Sails JS 护照 http 401

总是返回 401 Unauthorized in passport-jwt