我正在尝试使用passport-jwt身份验证策略对nodejs api进行身份验证,但它总是抛出401未经授权的错误。我尝试了各种实现,但是passport.authenticate功能似乎无法正常工作。
使用以下护照版本: "passport": "^0.4.0", "passport-jwt": "^4.0.0",
请查看我的代码:
尝试以下选项:
使用以下护照版本: "passport": "^0.4.0", "passport-jwt": "^4.0.0",
请查看我的代码:
尝试以下选项:
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
jwtFromRequest: ExtractJwt.fromHeader('authorization')
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer')
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt')
但是没有起作用。
尝试查看passport-jwt 401 Unauthorized和其他相关链接进行参考。
app.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:
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:
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文件:
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);
}