如何使用jwt/express/node从当前用户获取令牌



我有一个控制器,它接收一个试图通过表单登录的用户。当检查了所有验证后,用户将登录,并以以下方式创建令牌:

const token = jwt.sign({userId: user._id}, config.secret  ,{expiresIn: '24h'})
res.json({success: true, message: 'Sesión iniciada', token: token, user: {email: user.email}})
然而,我如何从另一个控制器访问这个令牌?我看到一个好的方法是创建一个中间件来拦截这样的令牌,但我真的不知道如何实现这一点。

我只知道如何得到令牌。我是新来的,我正在迈出很小的一步。

你应该设置你的客户端请求发送这样的令牌@Vahid说。

下面是axios

的例子
const instance = axios.create({
baseURL: 'https://some-domain.com/api',
// From the docs:
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
transformRequest: [function (data, headers) {
headers['Authorization'] = localStorage.getItem('jwt')
return data;
}],
})
export default instance

如果您还需要GET请求,您可以添加:

export setAuthToken = (token) => {
instance.defaults.headers.common['Authorization'] = token;
}

尽管每次更新JWT时都需要调用它。

之后,您可以使用中间件捕获它,从报头

解码令牌
app.use((req, res, next) => {
const authToken = req.headers['Authorization']
if(authToken) {
try {
const decoded = jwt.verify(authToken, config.secret)
req.user = decoded.userId
// Hopefully
// req.user = getUserById(decoded.userId)
next()
} catch(e) {
// Handle Errors or renewals
req.user = null
// You could either next() to continue or use 'res' to respond something
}

} else {
// Throw 403 if should be authorized
res.sendStatus(403)
}
})

这样,您应该能够在中间件之后定义的任何路由上访问req.user。如:

app.post('/me', (req, res) => {
res.send(req.user)
})

注意,这只是全局中间件的一个例子。在其他情况下,您应该能够根据您想要保护的路由或权限数量创建自定义中间件。