These are passport strategys. I think the problem is right here
`您好,我正在尝试在我的Web应用程序中实现passport-jwt。但这没用,我看过几篇相同的文章并尝试了他们的所作所为,但就我而言,它没有用。
这是一些带有password-jwt的身份验证节点API
没有调用护照本地策略
Passport-jwt未经授权
我已经尝试过了,但没有成功。这是我的护照上的代码。
import User from "../models/User";
import passport from 'passport';
const JWTSTrategy = require('passport-jwt').Strategy
import { ExtractJwt } from "passport-jwt";
const LocalStrategy = require('passport-local').Strategy;
const localLogin = new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
session: false,
}, async (email:any, password:any, done:any) => {
const user = await User.findOne({email: email})
if(!user) {
return done(null, false, { message: 'Not user found' })
} else {
const match = await user.matchPassword(password);
if(match) {
return done(null, user)
} else {
return done(null, false, { message: 'incorrect password' })
}
}
});
const loginJWT = new JWTSTrategy({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: `${process.env.TOKEN_SECRET}`
},
async (payload: any, done: any) => {
console.log(payload)
try {
const user = await User.findById({_id: payload._id});
if(!user) {
return done(null, false, { message: 'user not found' })
}
done(null, user)
} catch(err) {
done(err, false, { message: "something was wrong" })
}
}
)
passport.use(loginJWT); passport.use(localLogin);
export const authLocal = passport.authenticate('local', { session: false }); export const authJwt = passport.authenticate('jwt', { session: false });
我认为这里有问题
这些是路线
import { Router } from "express"
import { registerUser, loginUser } from "../controllers/auth.control"
import post from "../controllers/post.control"
import verify from "../controllers/verify.control"
import verifyToken from "../middlewares/verify-token"
import { authJwt, authLocal } from "../middlewares/passport";
const router = Router()
router.route('/post')
.get(post)
router.route('/register')
.post(registerUser)
router.route('/login')
.post(loginUser)
router.route('/profile').get(authJwt,
function(req:any, res: any) {
res.send(req.user)
})
export default router