gpt4 book ai didi

node.js - JWT token 在验证时始终无效

转载 作者:行者123 更新时间:2023-12-04 08:40:28 25 4
gpt4 key购买 nike

我是 node.js、express 和 JWT 的新手。我在这里发现了类似的问题,但没有帮助。

我能够登录并将 token 存储在本地存储中,但是当我尝试为另一个具有相同 token 的请求设置授权 header 时,它无法在服务器中进行验证。我从服务器和客户端检查了 token ,它们完全相同但是验证失败,请帮助!

这是我用来验证 token 的代码。

exports.verify = function(req, res, next) {
let accessToken = req.headers.authorization
if (!accessToken){
return res.status(403).send()
}

let payload
try{
// Never makes it through this

payload = jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET)
next()
}
catch(e){

return res.status(401).json({success: false, message: "token expired or invalid"})
}
}

app.js 文件中,我对另一条路线使用了这样的 verify 函数。

const { verify } = require('./controllers/auth')

const userRoutes = require('./routes/userRoutes')

app.use('/user', verify, userRoutes)

我哪里出错了?

编辑:

我在 verify 函数中添加了 console.log(e),在 catch() 中得到了以下结果。

TokenExpiredError: jwt expiredat /home/shashank/Documents/sms/server/node_modules/jsonwebtoken/verify.js:152:21at getSecret (/home/shashank/Documents/sms/server/node_modules/jsonwebtoken/verify.js:90:14)at Object.module.exports [as verify] (/home/shashank/Documents/sms/server/node_modules/jsonwebtoken/verify.js:94:10)at exports.verify (/home/shashank/Documents/sms/server/controllers/auth.js:62:23)at Layer.handle [as handle_request] (/home/shashank/Documents/sms/server/node_modules/express/lib/router/layer.js:95:5)at trim_prefix (/home/shashank/Documents/sms/server/node_modules/express/lib/router/index.js:317:13)at /home/shashank/Documents/sms/server/node_modules/express/lib/router/index.js:284:7at Function.process_params (/home/shashank/Documents/sms/server/node_modules/express/lib/router/index.js:335:12)at next (/home/shashank/Documents/sms/server/node_modules/express/lib/router/index.js:275:10)at cookieParser (/home/shashank/Documents/sms/server/node_modules/cookie-parser/index.js:57:14){ expiredAt: 2020-10-29T17:30:31.000Z }

让我展示一下我存储 key 信息的 .env 文件

ACCESS_TOKEN_SECRET=swsh23hjddnns
ACCESS_TOKEN_LIFE=3600
REFRESH_TOKEN_SECRET=dhw782wujnd99ahmmakhanjkajikhiwn2n
REFRESH_TOKEN_LIFE=86400

那么,访问 token 必须持续一个小时,对吧?

token 创建如下

const jwt = require('jsonwebtoken')

// Not using a database right now.
let users = {
email: 'myemail@gmail.com',
password: 'password'
}

exports.login = function(req, res) {

let email = req.body.email
let password = req.body.password

// Simple validation !
if (!email || !password || users.email !== email || users.password !== password){
return res.status(401).json({success: false, message: "Incorrect username or password"})
}


//use the payload to store information about the user such as username, user role, etc.
let payload = {email: email}

//create the access token with the shorter lifespan
let accessToken = jwt.sign(payload, process.env.ACCESS_TOKEN_SECRET, {
algorithm: "HS256",
expiresIn: process.env.ACCESS_TOKEN_LIFE
})

//create the refresh token with the longer lifespan
let refreshToken = jwt.sign(payload, process.env.REFRESH_TOKEN_SECRET, {
algorithm: "HS256",
expiresIn: process.env.REFRESH_TOKEN_LIFE
})

//store the refresh token in the user array
users.refreshToken = refreshToken

//send the access token to the client inside a cookie
// res.cookie("jwt", accessToken, { httpOnly: true}) //secure: false, use this along with httpOnly: true in production

// res.setHeader('Authorization', accessToken);
res.json({
accessToken: accessToken,
success: true, message: "Authentication success"
});
res.send()

}

最佳答案

看来您遇到的问题是因为您存储超时期限的方式。

来自 node-jsonwebtoken 的文档

expiresIn: expressed in seconds or a string describing a time spanzeit/ms. Eg: 60, "2 days", "10h", "7d". A numeric value is interpretedas a seconds count. If you use a string be sure you provide the timeunits (days, hours, etc), otherwise milliseconds unit is used bydefault ("120" is equal to "120ms").

因为您存储在您的 process.env 中,所以看起来它正在将其转换为字符串,而不是维护整数值。

测试代码:

const jwt = require('jsonwebtoken')
require('dotenv').config();
let payload = {email: 'email'}
let accessToken = jwt.sign(payload, process.env.ACCESS_TOKEN_SECRET, {
algorithm: "HS256",
expiresIn: process.env.ACCESS_TOKEN_LIFE
})
console.log(accessToken);
console.log('waiting 4 seconds');
setTimeout(function() {
let val = jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET);
console.log(val);
}, 4000);

使用以下 process.env 值,它会失败

ACCESS_TOKEN_SECRET=swsh23hjddnns
ACCESS_TOKEN_LIFE=3600
REFRESH_TOKEN_SECRET=dhw782wujnd99ahmmakhanjkajikhiwn2n
REFRESH_TOKEN_LIFE=86400

但是如果我们将 ACCESS_TOKEN_LIFE 更改为

ACCESS_TOKEN_LIFE=3600S

成功了

如果没有时间单位,任何延迟超过 3.6 秒的请求都会出错。

关于node.js - JWT token 在验证时始终无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64594060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com