[英]Where should I set the authorization header after create the token?
I am triying to implement a securuty system based on tokens.我正在尝试实施基于令牌的安全系统。 The problem is that I dont know where I must set the authorization header after create it in order to check it in all of my diferent routes.问题是我不知道在创建授权 header 之后我必须在哪里设置它,以便在我所有不同的路由中检查它。 My code is the next.我的代码是下一个。 I want to do it WITHOUT USING POSTMAN or any program like that.我想在不使用 POSTMAN 或任何类似程序的情况下进行。
This is the route for user login, where I create the token这是用户登录的路径,我在其中创建令牌
router.post('/login',(req,res)=>{
const user = req.body.user;
const token = jwt.sign({user},'secret_key');// generamos un identificador para el usuario que acaba de registrarse
res.json({
token
});
});
Then, I have this route to test it works然后,我有这条路线来测试它是否有效
router.get('/protected',ensureToken,(req,res)=>{
jwt.verify(req.token,'secret_key',(err,data)=>{
if(err){
res.sendStatus(403);
}else{
res.json({
text:'protected'
});
}
});
});
And finally, this is the middleware最后,这是中间件
function ensureToken(req,res,next){
const bearerHeader = req.headers['authorization'];
console.log(bearerHeader);
if(typeof bearerHeader != 'undefined'){
const bearer = bearerHeader.split(" ");
const bearerToken= bearer[1];
req.token = bearerToken; //almacenamos el token en el objeto de la peticion
next();
}else{
res.sendStatus(403);//status de no permitido
}
}
Where I should set the authorization header for all of my routes type 'get' as the protected route?我应该在哪里为我的所有路由类型“get”设置授权 header 作为受保护的路由?
router.get('/verify', async (req, res, next) => {
try {
const token = req.headers['x-access-token']//client should this value
if (!token){
return res.status(401).send({
success: false,
message: 'Unauthorized request',
})
}
else if (isExpiredToken(token)){
return res.status(300).send({
success: false,
message: 'Token is expired',
})
}
const decoded = jwt.verify(token, SECRET_KEY)
const expiredAt = moment.unix(decoded.exp).subtract(@YOUR_EXPIRED_TIME, 'minutes')
const now = moment()
let newToken = null
if (now.isAfter(expiredAt)) {//refresh the token
const userFromDB = await User.findOne({
where: {
id: decoded.id,
},
})
const content = util.sanitize(userFromDB)
newToken = await jwt.sign(content, SECRET_KEY, {
audience: content.email,
issuer: 'YOUR_APP',
expiresIn: 'YOUR_EXPIRED_TIME',
})
console.log(
`VERIFY\tToken refreshed automatically for user-${content.id}`
)
}
res.send({
success: true,
nextToken: newToken,
})
} catch (e) {
console.log(e)
res.status(500).send({
success: false,
message: 'Internal server error',
})
}
})
async function authMiddleware(req, res, next){
/* In this case, user can authenticate with header['x-access-token'] or body['accessToken']*/
const token = req.header['x-access-token'] || req.body['accessToken'] || undefined
if(!token) return res.status(401).send({ success: false, message: 'unauthorized' })
try{
const user = await jwt.verify(token, secret)
req.user = { ...user }
return next()
}
catch(e){
console.log(e)
return res.status(500).send({ success : false, message : 'internal server error' })
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.