[英]passport-jwt always return 401 unauthorized
I am trying to authenticate the nodejs api's using passport-jwt authentication strategy, but it always throws 401 unauthorized error.我正在尝试使用 passport-jwt 身份验证策略对 nodejs api 进行身份验证,但它总是抛出 401 未授权错误。 I tried various implementations but passport.authenticate function just doesn't seem to work.
我尝试了各种实现,但 passport.authenticate function 似乎不起作用。
Using below passport versions:使用以下护照版本:
"passport": "^0.4.0", “护照”:“^0.4.0”,
"passport-jwt": "^4.0.0", “护照-jwt”:“^4.0.0”,
Please see my code below:请在下面查看我的代码:
Tried below options:尝试了以下选项:
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
jwtFromRequest: ExtractJwt.fromHeader('authorization')
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer')
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt')
But not working.但没有工作。
Tried looking into passport-jwt 401 Unauthorized and other links for reference as well.尝试查看passport-jwt 401 Unauthorized和其他链接以供参考。
app.js file:应用程序.js 文件:
const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const cors = require('cors');
const app = express();
const login = require('./routes/login');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// app.use(passport.initialize());
app.use('/', login);
app.listen(8000, () => console.log('Server running on http://localhost:8000/'));
login.js file in route folder:路由文件夹中的 login.js 文件:
const express = require('express');
const router = express.Router();
const passport = require('passport');
const passportref = require('./../controllers/passport');
const loginController = require('./../controllers/loginController');
router.post('/putemailregistration',loginController.putEmailregistration);
router.get('/login', passportref.authenticate,loginController.verifyLogin);
module.exports = router;
Passport.js file:护照.js 文件:
const passport = require('passport');
const JWTStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const models = require('./../models');
const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'incredible',
}
passport.use(new JWTStrategy(opts,async (payload, done) => {
try {
console.log(`inside jwt strategy func`);
const user = models.Userabout.findById({
where: { email: { [Op.eq]: payload.email } },
attributes: ['id', 'email', 'password'],
});
console.log(`value of user: ${user}`);
if (typeof user !== 'undefined' && user !== null) {
return done(null, user);
}
else {
return done(null, false);
}
} catch (err) {
done(err, false);
}
}));
module.exports = {
initialize: () => passport.initialize(),
authenticate: passport.authenticate("jwt", { session: false }),
};
loginController.js file: loginController.js 文件:
const { Op } = require('sequelize');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const models = require('./../models');
const saltRounds = 10;
module.exports.putEmailregistration = async (req, res) => {
try {
console.log(`inside put email registration`);
if (req.body.email === null || req.body.password === null) {
res.sendStatus(400).json('no data');
} else {
const emailregister = await models.Userdata.create({
email: req.body.email,
password: bcrypt.hashSync(req.body.password,
bcrypt.genSaltSync(saltRounds)),
});
const tokenid = jwt.sign({
id: emailregister.id,
email: emailregister.email,
}, process.env.JWT_SECRETKEY,
{ expiresIn: 3600 });
res.json({ success: true, token: 'bearer ' + tokenid });
}
} catch (err) {
console.log(`error at put email registration: ${err}`);
}
}
module.exports.verifyLogin = (req, res) => {
console.log(`i managed to get here`);
// console.log(`user: ${req.user}`);
// res.send(req.user.email);
}
After lot of debugging, i finally resolved the issue.经过大量调试,我终于解决了这个问题。 Hope this might help someone
希望这可以帮助某人
To solve this you can manage it in your middle ware为了解决这个问题,你可以在你的中间件中管理它
function authorized(request, response, next) {
passport.authenticate('jwt', { session: false, }, async (error, token) => {
if (error || !token) {
response.status(401).json({ message: 'Unauthorized Message' });
}
try {
console.log('token',token)
const user = await User.findOne(
{_id: token._id}
);
request.user = user;
} catch (error) {
next(error);
}
next();
})(request, response, next);
}
router.get(
'/',
authorized,
trimRequest.all,
user.getItems
)
In my case, I was using expiresIn
value from the environment variable.就我而言,我使用的是环境变量中的
expiresIn
值。 The environment variable values will be of String
type and If we pass a string value to expiresIn
, it will be taken in milliseconds.环境变量值将是
String
类型,如果我们将字符串值传递给expiresIn
,它将以毫秒为单位。 So a value of 3600 was getting converted to 3 seconds and by the time I copy the token from the sign-in response to the auth header, it was getting expired.所以 3600 的值被转换为 3 秒,当我将令牌从登录响应复制到 auth 标头时,它已过期。
https://www.npmjs.com/package/jsonwebtoken#usage https://www.npmjs.com/package/jsonwebtoken#usage
使用passport.use('jwt',new JWTStrategy({opts},verify_callback(){})
在passport.js
In my case the error was calling done(null) instead of done(null, jwtPayload) which lead to 401s在我的例子中,错误是调用 done(null) 而不是 done(null, jwtPayload) 导致 401s
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: secret,
}, function (jwtPayload, done) {
done(null, jwtPayload); // I was calling just done(null)
})).authenticate('jwt', { session: false })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.