如何设置http only cookie

问题描述

我目前正在为应用实现登录/注册/注销功能,并使用 JWT。我的 MERN 应用程序在两个不同的端口上运行:前端 - 3000,后端 - 10000。我成功地从前到后发送和获取数据,但是在设置 httponly cookie 以在那里存储 JWT 令牌时,我看到了令牌,它的生成没有错误,我得到了成功的响应:

Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 44
Content-Type: text/html; charset=utf-8
Date: Tue,08 Jun 2021 18:40:02 GMT
ETag: W/"2c-4r7DVPOVNJvegkHqxvDpBQ6Yp8Y"
Keep-Alive: timeout=5
Set-Cookie: nToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwYmY1ZjNlNzU0NmFhMTMxY2M5M2U1MyIsImVtYWlsIjoic29tZWVtYWlsQGdtYWlsLmNvbSIsImlhdCI6MTYyMzE3NzYwMSwiZXhwIjoxNjU0NzM0NTI3fQ.9uNwg6PIfGDJnmbt8qNd4IDt_9JDHuno_IUL9FSwz-U; Max-Age=900; Path=/; Expires=Tue,08 Jun 2021 18:55:02 GMT; HttpOnly
X-Powered-By: Express

一些日志以确保一切正常:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwYmY1ZjNlNzU0NmFhMTMxY2M5M2U1MyIsImVtYWlsIjoic29tZWVtYWlsQGdtYWlsLmNvbSIsImlhdCI6MTYyMzE3NzYwMSwiZXhwIjoxNjU0NzM0NTI3fQ.9uNwg6PIfGDJnmbt8qNd4IDt_9JDHuno_IUL9FSwz-U
POST /api/user 200 4311.690 ms - 44

最后,访问 /api/user 时调用的 controller.js 文件部分:

getone: async (req,res) => {

    try {
      const user = await User.findOne({ email: req.body.user.email });
      if (!user) {
        return "User doesn't exist";
      }
      // Check password
      const isMatch = await bcrypt.compare(
        req.body.user.password,user.password
      );
      console.log(req.body.user.password,user.password,isMatch);
      if (isMatch) {
        // User matched
        // Create JWT Payload
        const payload = {
          id: user._id,email: user.email,};
        // Sign token
        try {
          const token = await jwt.sign(payload,process.env.SECRET,{
            expiresIn: 31556926,// 1 year in seconds
          });
          console.log(token)
           res.cookie('nToken',token,{ maxAge: 900000,httpOnly: true });
          return `Succesfully logged in as ${user.email}`
        } catch (err) {
          return err.message;
        }
      } else {
        return "Wrong password";
      }
    } catch (err) {
      return "Error: " + err.message;
    }
  },

它实现了登录功能

所以我问这个问题为什么我在 devtools->cookies 中没有看到 httponly cookie 我的 useEffect 调用后端:

useEffect(async () => {
    const articles = await axios({method: "POST",url: vars.BACKENDURL + "/user",data: { user: {
    email: "[email protected]",password: "mypass123"
}
}});

前端得到的响应:

config:
adapter: ƒ xhrAdapter(config)
data: "{\"user\":{\"email\":\"[email protected]\",\"password\":\"mypass123\"}}"
headers:
Accept: "application/json,text/plain,*/*"
Content-Type: "application/json;charset=utf-8"
__proto__: Object
maxBodyLength: -1
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: [ƒ]
transformResponse: [ƒ]
url: "http://localhost:10000/api/user"
validateStatus: ƒ validateStatus(status)
xsrfCookieName: "XSRF-TOKEN"
xsrfheaderName: "X-XSRF-TOKEN"
__proto__: Object
data: "Succesfully logged in as [email protected]"
headers: {content-length: "44",content-type: "text/html; charset=utf-8"}
request: XMLHttpRequest {readyState: 4,timeout: 0,withCredentials: false,upload: XMLHttpRequestUpload,onreadystatechange: ƒ,…}
status: 200
statusText: "OK"

  • 由于某种原因,网络中显示了两个对用户 api 的请求,这是第二个:

Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Tue,08 Jun 2021 18:39:57 GMT
Keep-Alive: timeout=5
vary: Access-Control-Request-Headers
X-Powered-By: Express

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)