简体   繁体   English

如何在本机中处理cookie?

[英]How cookies are handled in react-native?

I have a web app running with node js and passport.js and the authentication flow is working well. 我有一个使用节点js和passport.js运行的Web应用程序,并且身份验证流程运行良好。 I'm trying to develop a react-native and to make the same authentication flow (with passport.js). 我正在尝试开发一个本机反应,并进行相同的身份验证流程(使用passport.js)。

I changed the passport code to redirect back to the react-native app (with Linking) and it worked. 我更改了护照代码,以重定向回react-native应用程序(具有Linking),并且它可以正常工作。

so the flow is: 因此流程为:

  1. Open browser with the login url (/auth/google) 使用登录网址(/ auth / google)打开浏览器
  2. User logged in 用户登录
  3. Redirected back to native app 重定向回本机应用
  4. send a request to verify the user is logged in - but the user is not logged in, I think because the cookies were not sent to the server 发送请求以验证用户已登录-但用户未登录,我认为是因为未将Cookie发送到服务器

I also tried adding to the fetch credentials "same-origin" or "include" but still the user is not logged in. 我还尝试将提取凭证添加为“ same-origin”或“ include”,但用户仍未登录。

Some code I used: 我使用的一些代码:

Linking.openURL("http://<my ip>:3000/auth/google"); //for log in

app.get('/auth/google/callback', //handle the log in with passport js
    passport.authenticate('google', {
        failureRedirect: '/login'
    }), function(req, res) {
        res.redirect('MyApp://login); // redirect back to native app
    });

fetch("http://<my ip>:3000/api1", {credentials: /*"same-origin"*/"include"}) //get 401 -> user is not logged in

Am I missing anything? 我有什么想念的吗?

How cookies are handled in react-native? 如何在本机中处理cookie? Is it like in the web? 就像在网络上吗? how the cookies should be passed from the browser to the native app after redirect? 重定向后应如何将Cookie从浏览器传递到本机应用程序?

React Native is not browser environment. React Native不是浏览器环境。 It doesn't automatically handle cookies like browsers. 它不会自动处理浏览器之类的Cookie。

You have to use some cookie-aware request library such as superagent . 您必须使用一些支持cookie的请求库,例如superagent

Example usage (from superagent documentation ): 用法示例(来自superagent文档 ):

const agent = request.agent();
agent
  .post('/login')
  .then(() => {
    return agent.get('/cookied-page');
  });

Then all requests from agent will handle cookies automatically (shares the same cookie jar). 然后,来自agent所有请求将自动处理cookie(共享同一个cookie jar)。

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

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