我有一个使用 Next JS 的项目,我正在为 Next JS 构建 API。我想添加一个身份验证功能,以便只有登录的用户才能访问 API。我正在尝试,我正在使用 jsonwebtoken、passport 和passport-jwt。成功登录后,我得到一个 accessToken,但是当我在 Authorization 标头中使用它时,服务器以 Unauthorized 响应。任何解决方案?
passportStrategy.js
import UserService from '@services/UserService';
import passport from 'passport';
import passportJwt from 'passport-jwt';
const JwtStrategy = passportJwt.Strategy;
const { ExtractJwt } = passportJwt;
passport.serializeUser((user, done) => {
done(null, user.username);
});
passport.deserializeUser((username, done) => {
done(null, username);
});
const options = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken,
secretOrKey: process.env.ACCESS_KEY,
};
passport.use(new JwtStrategy(options, async (jwtPayload, done) => {
const expirationDate = new Date(jwtPayload.exp * 1000);
if (expirationDate < new Date()) {
return done(null, false);
}
const user = await new UserService().getCurrentUser(jwtPayload.username);
return done(null, user);
}));
export default passport;
auth.js
import nextConnect from 'next-connect';
import passport from '@utils/passportStrategy';
const auth = nextConnect()
.use(passport.initialize())
.use(passport.session())
.use(passport.authenticate('jwt'));
export default auth;
pages/api/projects/index.js
const handler = nextConnect();
const projectService = new ProjectService();
handler.use(auth)
.get(async (req, res) => {
try {
const projects = await projectService.getProjects();
return res.status(200).json({
success: true,
length: projects.length,
data: {
projects,
},
});
} catch (error) {
return res.status(500).json({
success: false,
message: error.message,
});
}
})
...