【问题标题】:JWT gives invalid tokenJWT 提供无效令牌
【发布时间】:2020-05-25 02:36:10
【问题描述】:

在本地工作,我的 jwt 令牌无效,但在 jwt.io 中显示已验证签名。不知道我错过了什么。每当我尝试调用应用程序中的 api 时,我的签名无效。

链接.js

const { Router } = require("express");
const Link = require("../models/Link");
const auth = require("../middleware/auth.middleware");
const router = Router();

router.get("/", auth, async (req, res) => {
try {
const links = await Link.find({ owner: req.user.userId });
res.json(links);
} catch (error) {
res.status(500).json({ message: "Something went wrong, try again" });
}
});

auth.middleware.js

const jwt = require("jsonwebtoken");
const config = require("config");


module.exports = (req, res, next) => {
if (req.method === "OPTIONS") {
return next();
}

try {
const token = req.headers.authorization; // Token

if (!token) {
  return res.status(401).json({ message: "No Authorization" });
}

const decoded = jwt.verify(token, config.get("secret"));

req.user = decoded;
next();
} catch (error) {
res.status(401).json({ message: "No Authorization" });
}
};

链接.tsx

const LinksPage: React.FC = () => {
const [links, setLinks] = useState([]);
const fetchLinks = useCallback(async () => {
try {
  const fetched = await request("http://localhost:5000/api/link/", "GET", null, {
    Authorization: Token,
  });
  setLinks(fetched);
} catch (error) {
  alert(error);
}
}, []);
};

【问题讨论】:

  • 您是否将其用作 Bearer 令牌?如果是这样,请确保在验证之前从令牌字符串中删除任何不必要的字符。
  • 令牌是如何创建的?确切的错误信息是什么?
  • 如果您不回复 cmets 和答案,很难提供帮助

标签: reactjs typescript jwt


【解决方案1】:

也许“req.headers.authorization”不是您想要的。 在 chrome、firefox 中尝试 console.log(req.headers.authorization) F12。

我建议你也POSTMAN(免费软件)。它对调试后端(服务器端)帮助很大。

【讨论】:

    【解决方案2】:

    我解决了这个问题。我必须对存储在客户端中的 json.parse(token) 进行 jwt.verify(token, secret),但我正在验证包含令牌对象和 userId 的字符串。

    【讨论】:

      猜你喜欢
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2021-09-25
      • 1970-01-01
      • 2019-03-19
      • 2018-07-14
      • 2020-04-19
      相关资源
      最近更新 更多