我为用户使用Passport和JWT Auth系统内置了Node API。
用户可以注册并登录。
我的问题是关于刷新令牌以及处理它的最佳方法。
我所做的是将刷新令牌作为称为/refresh
的端点,但不确定该流程是否正确。
应该将刷新令牌包含在Login端点上,还是按照我的建议完成?
我想了解制作它的最佳方法以及应该继续处理的正确流程。
我的API上的Auth流代码:
路线
export default (app) => {
app.use('/', route);
app.use(passport.initialize());
app.post('/register', Controller.AuthCtrl.registerUser);
app.post(
'/login',
auth.basic,
auth.setUserInfo,
Controller.AuthCtrl.loginUser,
);
app.post(
'/refresh',
passport.authenticate('jwt'),
Controller.AuthCtrl.refreshToken,
);
};
控制器:
const AuthController = {
async registerUser(req, res, next) {
try {
const userSchema = {
...req.body,
createdAt: new Date(),
updatedAt: new Date(),
};
const user = await DB.User.register(userSchema, req.body.password);
// eslint-disable-next-line no-underscore-dangle
const token = auth.getToken({ _id: req.user._id });
if (!user) {
Logger.error('User was not created. Something went wrong');
return res
.status(500)
.send('User was not created. Something went wrong');
}
if (!token) {
Logger.error('Token was not created. Something went wrong');
return res
.status(500)
.send('Token was not created. Something went wrong');
}
Logger.info('User and token created successfully.');
return res.status(200).send({ user, token });
} catch (err) {
Logger.error(err);
return next(err);
}
},
async loginUser(req, res, next) {
try {
// eslint-disable-next-line no-underscore-dangle
const token = auth.getToken({ _id: req.user._id });
Logger.info(token);
if (!token) {
Logger.error('Token was not created. Something went wrong');
return res
.status(401)
.send('Token was not created. Something went wrong');
}
return res.status(200).send({ user: req.user, accessToken: token });
} catch (err) {
Logger.error(err);
return next(err);
}
},
async refreshToken(req, res, next) {
try {
// eslint-disable-next-line no-underscore-dangle
const token = auth.getToken({ _id: req.user._id });
Logger.info(token);
if (!token) {
Logger.error('Token was not created. Something went wrong');
return res
.status(401)
.send('Token was not created. Something went wrong');
}
return res.status(200).send({ user: req.user, accessToken: token });
} catch (err) {
Logger.error(err);
return next(err);
}
},
};
如果您需要添加其他信息,请在评论中让我知道。
但是,我想根据性能和可伸缩性来学习应该遵循的实践方法,或者我应该了解哪些实践可以提高我的开发技能。