【问题标题】:Not able to store json web token in cookies in my browser无法在浏览器的 cookie 中存储 json Web 令牌
【发布时间】:2021-07-11 07:46:01
【问题描述】:

所以我正在学习使用 cors npm 在 MERN 项目中用户登录的 JWT 身份验证。我能够生成 jwt 并且还能够将其存储在数据库中,但我无法看到我的 cookie 存储在浏览器。

这是我的 generateAuthToken() 函数存在于 express 服务器的模式文件中,这里我正在生成一个 jwt 并返回它 -

userSchema.methods.generateAuthToken = async function(){
try{
        //generate token
        const token = jwt.sign({_id:this._id.toString()} , process.env.SECRET_KEY);
        
        //stored the generated token in our document
        this.tokens = this.tokens.concat({token : token});

        //saved the changes made in the document
        await this.save();

        //returning the token generated when called
        return token;

}catch(err){
    console.log(err);
}

}

并在 express 服务器中的 index.js 中调用 generateAuthtoken() 函数。返回的令牌存储在“令牌”中 -

const token = await userLogin.generateAuthToken();
        //console.log(token);


    //storing logged in tokens inside cookies
        res.cookie("logintoken" , token , {
            expires : new Date(Date.now() + 60000), //60sec from the time we store the token inside the cookie
            httpOnly : true
        });

在前端反应代码中,我在 fetch api 中发送一个凭据标头,它调用我的快速服务器中端口 4000 上存在的登录路由-

const response = await fetch('http://localhost:4000/login',{
                method : "POST",
                credentials: 'include',
                headers : {
                    "Content-Type" : "application/json"
                },
                body : JSON.stringify({
                        email : email,
                        password : password
                })
        });

我正在使用 cors npm 包在我的 express 服务器中进行跨区域请求 -

   const cors = require('cors');

   app.use(cors());

在我的浏览器控制台中,我遇到了这个错误 -

但是当我检查我的浏览器时,cookie 没有存储在存储中 -

总而言之,我正在生成一个 jwt 并将其返回到函数中。然后将返回的令牌存储在名为“logintoken”的 cookie 中。但是该 cookie 没有存储在浏览器中。

我正在对此进行研究,并且能够找到一些线程说明我们还必须在 cors 中定义一些标头,以便浏览器能够存储 cookie。但我也无法弄清楚如何添加至于实现这一点需要哪些标头。我以前使用过 cookie 和 jwt ,但这是我第一次学习 react 、 express 和 cors npm。谢谢您的回复。

【问题讨论】:

  • 看看这个包CORS
  • @Medi 我阅读了“配置选项”部分,其中谈到了“访问控制允许来源”,但无法理解它。你能给我举个例子吗如何使用它 ?谢谢你的回复。我引用了这个链接 - stackoverflow.com/questions/46288437/…

标签: reactjs express cookies jwt cors


【解决方案1】:

这是我当前应用的代码 sn-p

app.use(
    cors({
        credentials: true,
        origin: `http://${process.env.REACT_APP_SERVER_HOST}:${process.env.PORT}`,
    })
);

【讨论】:

  • 所以我需要把我的前端响应 http 地址放在 origin 内,对吧?
  • 相信在使用cookies的情况下它不接受all-origin*值。
  • 我添加了 app.use(cors({ credentials : true, origin:'http://localhost:3000' })); cookie 被存储在浏览器中,但出现了一条警告,指出 Cookie “logintoken” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute.
  • 我添加了SameSite : 'none',现在出现了一个错误提示cors request didnot success
  • 尝试设置为SameSite=Lax?
猜你喜欢
  • 2017-10-19
  • 1970-01-01
  • 2014-09-18
  • 2021-10-13
  • 2021-06-29
  • 2021-06-04
  • 2018-10-30
  • 1970-01-01
  • 2021-09-10
相关资源
最近更新 更多