如何在反应端验证访问令牌?不危险吗?

How to verify an access token in react side? Isnt it dangerous?

目前我有一个后端,我可以使用这个简单的函数验证访问令牌:

const { verify } = require("jsonwebtoken");

const isAuth = req => {
  const authorization = req.headers["authorization"];
  if (!authorization) throw new Error("You need to login");

  const token = authorization.split(" ")[1]; //Bearer token123123jjjjasd , we get the token value
  const { userId } = verify(token, process.env.ACCESS_TOKEN_SECRET);
  return userId;
};

module.exports = {
  isAuth
};

但是在前端做那件事/反应来保护我的路线怎么样?将秘密存储在我的前端不是很危险吗? 我应该在我的后端创建一个验证路由并向那里发送访问令牌和 return 如果有效则为真,否则为假?这样安全吗?

我认为,正如您所说,最好在您的后端有一个路由来检查用户是否被授权。因为,正如文档所说,在 React 应用程序中存储 api 密钥和此类内容并不安全。

来自create-react-app documentation

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

您不应该在客户端存储 JWT 机密。放在客户端不安全

而且您不需要客户端的 JWT 密码。

您可以使用 jwt-decode 包在客户端解码令牌。

或者想不使用包解码的可以看.

要保护 React 中的路由,您可以创建一个 ProtectedRoute 组件,如本 中所述。

此外,最佳做法是生成具有较短到期时间的令牌。