繁体   English   中英

Node.js:JWT 与 Express - 验证时出现“无效令牌”错误

[英]Node.js: JWT with Express - “Invalid Token” Error when verifying

只是尝试使用 Express 服务器对 JSON web 令牌进行签名和验证的基本实现,但“验证”function 令牌不断返回“无效”令牌错误。

When pasting the generated token from the '/' route into the jwt.io debugger it initially says 'invalid signature' but when I check the 'secret is base64 encoded' checkbox, the debugger validates the signature, so I've tried base64 encoding /在签名和验证端解码我的秘密,但没有任何效果。

我目前正在使用名为“REST Client”的 VS 代码扩展名执行请求,该扩展名允许您使用“.rest”或“.http”文件发出请求,并且我正在将“Bearer [token]”手动传递给授权 header . 我也在使用 Postman 进行测试并收到相同的错误。 该应用程序按预期通过两种方法获取 header。

const express = require('express')
const jwt = require('jsonwebtoken')

const app = express()

app.use(express.json())

app.get('/', (req, res) => {
  const user = {
    username: 'test1234',
    email: 'test1234@gmail.com',
    admin: false
  }

  const secret = 'secret'

  jwt.sign(user, secret, (err, token) => {
    req.token = token
    res.send(token)
  })
})

app.get('/verify', (req, res) => {
  // Bearer <token>
  const authHeader = req.headers.authorization
  console.log(authHeader)
  if(authHeader) {
    const token = authHeader.split(' ')[1]
    const secret = 'secret'
    const userData = jwt.verify(token, secret)
    res.send(userData)
  } else {
    return res.send('Please provide a token.')
  }
})

app.listen(3000, () => console.log('Server listening on http://localhost:3000 ...'))

我期望从“/验证”路由返回有效负载(userData),但会收到“无效令牌”错误。

更新:问题是我将授权 header 的值用引号括起来,例如。 授权:“Bearer [token]”,当它不应该用引号引起来时,例如。 授权:不记名 [token]。

问题是我将授权 header 的值用引号括起来,例如。 授权:“Bearer [token]”,当它不应该用引号引起来时,例如。 授权:不记名 [token]。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM