【问题标题】:How to use Cookie for store jwt token user authentication?如何使用 Cookie 进行存储 jwt 令牌用户认证?
【发布时间】:2021-03-10 06:41:28
【问题描述】:

我用 reactjs 做了一个 Jwt 代币项目。所以我使用本地存储来记录 jwt 令牌身份验证,以便延迟检索。

我在帖子中记录了所有工作:https://loizenai.com/reactjs-jwt-authentication-example/

但是,我的同事告诉我,将 jwt 令牌保存在本地存储中并不安全。 有什么建议给我为什么,并给出一个正确的解决方案!

非常感谢!

【问题讨论】:

    标签: reactjs security authentication jwt local-storage


    【解决方案1】:

    服务器应生成一个 jwt 令牌并将其作为 cookie 返回给您的客户端:

    const maxAge = 3 * 24 * 60 * 60; // 3天

    return res.cookie('jwtToken', token, { 最大年龄:最大年龄 * 1000, httpOnly:是的, });

    客户:

    import Cookies from 'js-cookie';
    import jwtDecode from 'jwt-decode';
    
     const authUser = () => {
        const token = Cookies.get('jwtToken');
        let isAuth;
    
        if (token) {
          const decodedToken = jwtDecode(token);
          if (decodedToken.id) isAuth = true;
          else isAuth = false;
        } else {
          // console.log('jwt cookie not available');
          isAuth = false;
        }
        return isAuth;
      };
    
    

    【讨论】:

    猜你喜欢
    • 2022-09-11
    • 2016-04-06
    • 2019-09-14
    • 2015-09-15
    • 2016-09-13
    • 1970-01-01
    • 2016-12-13
    • 2018-11-01
    • 2021-12-07
    相关资源
    最近更新 更多