简体   繁体   English

Chrome 获取 Set-cookie 标头但未将其放入新请求中

[英]Chrome get Set-cookie header but doesnt put it in a new requests

I m working a Mobile app using React Native at the front end, NodeJs at the back end.我正在使用前端使用React Native和后端使用 NodeJ 的移动应用程序。 I put an authentication mechanism for this app.我为这个应用程序设置了身份验证机制。 Back-end works fine.后端工作正常。 I've tested with the postman.我已经用邮递员测试过。 After login request with correct data, the server sends me a cookie in " Set-cookie" header .使用正确数据登录请求后,服务器在“ Set-cookie”标头中向我发送一个 cookie。 Then I put my next request header as "cookie" and I got my data.然后我把我的下一个请求标头作为“cookie”,我得到了我的数据。 However, it works differently when I m working with React Native part.但是,当我使用 React Native 部分时,它的工作方式有所不同。 I m using Chrome browser to test app for now, and I can see that browser gets a set-cookie header with the response from Login request, (plus I've seen server created a new cookie with user info in it).我现在正在使用Chrome 浏览器来测试应用程序,我可以看到浏览器获取了一个 set-cookie 标头,其中包含来自登录请求的响应(另外我已经看到服务器创建了一个包含用户信息的新 cookie)。 But for the next request (say its "/home"), it doesn't send the cookie back, so the server doesn't recognize the user and creates a new cookie (with no user info in it) and returns 403 response.但是对于下一个请求(比如它的“/home”),它不会发回 cookie,因此服务器无法识别用户并创建一个新的 cookie(其中没有用户信息)并返回 403 响应。

There are some solutions that people suggest that you should do.人们建议您应该执行一些解决方案。 I m sharing those here but none of them worked for me.我在这里分享这些,但没有一个对我有用。

  1. put with withCredentials: true in your request or axios object (didnt solve the problem) put with withCredentials: true在您的请求或 axios 对象中(没有解决问题)
  2. set httpOnly:false for cookie in server (didnt solve the problem)在服务器中为 cookie 设置httpOnly:false (没有解决问题)
  3. set corsOptions as var corsOptions = { origin: '*',credentials: true, exposedHeaders: ["Set-Cookie"] };将 corsOptions 设置为 var corsOptions = { origin: '*',credentials: true, exposedHeaders: ["Set-Cookie"] }; (still not working) (还是行不通)
  4. I also use universal-cookie library to reach cookie data from front end, but it also cannot reach the cookie value我也使用universal-cookie库从前端获取cookie数据,但是也无法到达cookie值
  5. Using 127.0.0.1 instead of "localhost" in url also doesnt work (some says cookies dont work in first level domains)在 url 中使用127.0.0.1 而不是“localhost”也不起作用(有人说 cookie 在一级域中不起作用)

Here is my React Native - Axios code这是我的 React Native - Axios 代码

const axiosObj = axios.create({
    baseURL:"http://localhost:3000/",
    headers: {
      'Content-Type': 'application/json',
    },
    responseType: 'json',
    withCredentials: true, 
  });

export function get(url){
    return new Promise(function(resolve,reject){
        axiosObj.get(url).then(res => {
            console.log(res)
            return res.data
        })
    }) 
};

export function post(url,data){
    return new Promise(function(resolve,reject){
        axiosObj.post(url,data).then(res => {
            console.log(res.headers)
            const cookies = new Cookies(res.headers.cookie);
        console.log("document cookie",document.cookie)    
        console.log(cookies.getAll()); 
            resolve(res)
        })
    }) 
}

At the back end here are the related codes在后端这里是相关的代码

 var app = express();
app.use(cookieParser('keyboard cat'));


var corsOptions = {
  origin: '*',
  credentials: true,
  exposedHeaders: ["Set-Cookie"]
 };
app.use(cors(corsOptions))
app.use(logger('dev'));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

//session settings
app.use(session({
  genid: (req) => {
    console.log('Inside the session middleware')
    console.log(req.sessionID)
    return uuidv4(); // use UUIDs for session IDs
  },
  store: new FileStore(),
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { httpOnly: false,
    expires: new Date(Date.now() + (30 * 86400 * 1000))}
}))

This is my session file at the server after Login这是我登录后在服务器上的会话文件

{"cookie":{"originalMaxAge":2591995208,"expires":"2020-09-22T20:22:56.993Z","httpOnly":false,"path":"/"},"passport":{"user":{"_id":"5f307fc99f5c667918a56122","username":"test","__v":0}},"__lastAccess":1598214181785}

What can be the problem here?这里可能有什么问题? Any ideas?有任何想法吗?

edit : I've learned that not reaching "Set-cookie" is normal from front-end (JS).编辑:我了解到从前端(JS)没有达到“Set-cookie”是正常的 (although in some websites, its said that you can put httpOnly: false in cookie settings and it solves this problem). (尽管在某些网站中,它说您可以在 cookie 设置中设置httpOnly: false并解决此问题)。 So it actually doesn't matter if I don't reach the header inside the front end code.因此,如果我没有到达前端代码中的标题,实际上并不重要。 I got "set-cookie" header in my response header and chrome doesn't recognize the cookie and put it in cookies section in f12 (also doesn't set it in req.header).我的响应标头中有“set-cookie”标头, chrome 无法识别 cookie 并将其放在 f12 的 cookies 部分(也没有在 req.header 中设置)。 That's the problem here这就是问题所在

Edit 2: I have some ideas about my problem.编辑 2:我对我的问题有一些想法。

  • Since I m working with React Native and its not supposed to work in the Chrome browser, it might somehow cause that the browser is not setting cookies.由于我正在使用 React Native 并且它不应该在 Chrome 浏览器中工作,因此可能会以某种方式导致浏览器未设置 cookie。 I will create a react project and try to reach the cookie from there.我将创建一个反应项目并尝试从那里访问 cookie。 => I solved the problem it was not related to that issue. =>我解决了与该问题无关的问题。 Although I solved problem when I was testing with react an app虽然我在测试应用程序时解决了问题

  • I got a "service-worker.js" error with my react-native code.我的 react-native 代码出现“service-worker.js”错误。 It doesn't look like it affects the functionality of the code but it might be somehow affected this cookie situation => After solving the problem I still got this error, so it was not related to this.看起来它不会影响代码的功能,但它可能会以某种方式影响这种 cookie 情况 =>解决问题后,我仍然遇到此错误,因此与此无关。

I also tried a react native app for cookies (react-native-cookie) but it has codes only working with android or ios so it didn't work for the browser.我还尝试了用于 cookie 的本机应用程序 (react-native-cookie),但它的代码仅适用于 android 或 ios,因此不适用于浏览器。

I solved my problems.我解决了我的问题。 It looks like i have 2 problems with my code.看起来我的代码有两个问题。 First one is in server with cors settings.第一个是在带有 cors 设置的服务器中。 The first version was like this :第一个版本是这样的:

var cors = require('cors');
var corsOptions = {
  origin: '*',
  credentials: true,
  exposedHeaders: ["set-cookie"]
 };
app.use(cors(corsOptions))

So basically I was using the cors module for settings.所以基本上我使用 cors 模块进行设置。 When I create a React app for the test I got a cors error(origin error).当我为测试创建一个 React 应用程序时,我收到了一个 cors 错误(原点错误)。 Somehow my cors settings didn't work with the library.不知何故,我的 cors 设置不适用于图书馆。 So I changed this code with the below.所以我用下面的代码更改了这段代码。

app.use(function (req, res, next) {
     // Website you wish to allow to connect
     res.setHeader('Access-Control-Allow-Origin', '*');
     // Request methods you wish to allow
     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
     // Request headers you wish to allow
     res.setHeader('Access-Control-Allow-Headers', 'Origin,X-Requested-With,content-type,set-cookie');
     // Set to true if you need the website to include cookies in the requests sent
     // to the API (e.g. in case you use sessions)
     res.setHeader('Access-Control-Allow-Credentials', true);
  
     // Pass to next layer of middleware
     next();
   });

and I still had some cors error.我仍然有一些 cors 错误。 One other reason you might get a cors error is that chromes same-origin policy.您可能会收到 cors 错误的另一个原因是 chromes 同源策略。 I m using windows 10 so I opened search bar below and paste there我使用的是 Windows 10,所以我打开了下面的搜索栏并粘贴到那里

 chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

A new chrome browser opened with no web security policy.一个新的 chrome 浏览器打开,没有网络安全策略。 Then my react app worked fine.I could reach the cookie using document.cookie , also in f12 under application tab >> cookies, I could be able to see my cookie.然后我的反应应用程序工作正常。我可以使用document.cookie访问 cookie,也在应用程序选项卡 >> cookie 下的 f12 中,我可以看到我的 cookie。 So google chrome saved my cookie.所以谷歌浏览器保存了我的 cookie。 In the same chrome window, I run my react native app and it also worked successfully.在同一个 chrome 窗口中,我运行我的本机应用程序,它也成功运行。 So I thought it was only because security policy of chrome and change my cors settings back and I started to get an error again.所以我认为这只是因为 chrome 的安全策略并将我的 cors 设置改回来,我又开始出现错误。

So in conclusion, I had to change 2 things.所以总而言之,我必须改变两件事。

  1. Cors module didn't work, I set headers manually and they worked fine. Cors 模块不起作用,我手动设置标题并且它们工作正常。
  2. I had to disable Chrome's same-origin policy我不得不禁用 Chrome 的同源策略

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM