处理 cookie 中 JWT 令牌以进行客户端身份验证的正确方法

发布于 2025-01-10 18:13:23 字数 1189 浏览 0 评论 0原文

我有一个后端,在成功验证后会使用 JWT 令牌进行响应。但是,出于安全目的,cookie 在客户端是不可见的。现在在前端我使用react。我创建了一个设置和获取令牌的功能组件。我了解到,存储 JWT 令牌的最佳方法是将其保存为 cookie 并从服务器端激活 HTTPOnly。我的问题是为了保护 JWT 令牌,如果激活了 HTTPOnly(这使得 cookie 不可见),如何在前端正确保存 cookie?我打算使用cookie来检查用户是否已经登录。只是为了让您了解我正在做的事情,我添加了下面的组件。


export default function useToken() {
    const getToken = () => {
        const tokenString = localStorage.getItem("token"); // I will refactor localstorage to cookie
        const userToken = JSON.parse(tokenString as string);
        return userToken;
    }

    const [token, setToken] = useState<string>(getToken());

    const saveToken = (userToken: string) => {
        localStorage.setItem("token", JSON.stringify(userToken)); // I will refactor localstorage to cookie
        setToken(userToken)
    }
    return {
        setToken: saveToken, 
        token
    }
}


......

  const { token, setToken } = useToken()
  return (
    <div className="app">
      <Header />
      <Footer />

      <Router>
        <Routes>
          <Route path="/login" element={!token ? <Login setToken={setToken} /> : <Navigate to="/" />} />

.....

I have a backend that responds with a JWT token upon successful authentication. However, for security purposes, the cookie can not be visible from the client-side. Now in the frontend I use react. I have created a functional component that sets and gets a token. I have learned that the best approach to store the JWT token is to save it as a cookie as well as activate HTTPOnly from server side. The question I have is for the purpose of securing the JWT token how can I properly save the cookie in the frontend if the HTTPOnly is activated (which makes the cookie not visible)? I plan to use the cookie to check if the user is already logged in or not. Just to give you an overview of what I am doing I have added the component below.


export default function useToken() {
    const getToken = () => {
        const tokenString = localStorage.getItem("token"); // I will refactor localstorage to cookie
        const userToken = JSON.parse(tokenString as string);
        return userToken;
    }

    const [token, setToken] = useState<string>(getToken());

    const saveToken = (userToken: string) => {
        localStorage.setItem("token", JSON.stringify(userToken)); // I will refactor localstorage to cookie
        setToken(userToken)
    }
    return {
        setToken: saveToken, 
        token
    }
}


......

  const { token, setToken } = useToken()
  return (
    <div className="app">
      <Header />
      <Footer />

      <Router>
        <Routes>
          <Route path="/login" element={!token ? <Login setToken={setToken} /> : <Navigate to="/" />} />

.....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠栀 2025-01-17 18:13:24

要检查用户是否已经登录,一种常见的方法是:

只要后端的一个请求返回 HTTP 401,就认为用户已注销。

此外,这还取决于您的前端是否位于 CDN 中或在页面加载时访问服务器。对于后一种情况,您可以在服务器端找到它。

然后,为了处理身份验证,您的服务器可以在收到请求时从 cookie 中读取 JWT 令牌。

To check if the user is already logged in or not, one common way is :

as soon as one request from the backend returns HTTP 401, the user is considered logged out.

Also, it depends if your frontend is in a CDN or hitting the server on page load. On the latter case, you can find it out server-side.

Then, to handle authentication, your server can read the JWT token from the cookies when receiving the request.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文