gpt4 book ai didi

node.js - Passport -jwt 续集 401 始终

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:39 24 4
gpt4 key购买 nike

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

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;

使用 postman :标题: 身份验证:JWT token

本地主机:4040/api/用户

最佳答案

您是否在 header 部分配置了 postman ?你能展示 JwtStrategy 代码吗?

关于node.js - Passport -jwt 续集 401 始终,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50481525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com