9

I am having a hard time getting cookies to work, on the server side I use them to verify the user by grabbing them from req.cookies.

Here is how I currently set it on the Login.js file in React Native:

import Cookies from "universal-cookie";

const cookies = new Cookies();
 cookies.set("token", token, {
                expires: 7, // 7 days
                path: "/"
                //,secure: true // If served over HTTPS
   });

This works fine when I call a cookies.get("token") on this page. However, when I import, setup the const, and call get on another page the token does not show up...

Also, when I make the fetch like this:

fetch("http://192.168.0.115:3000/myTransactions/", {
      credentials: "same-origin",
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    })

The server does not receive any cookies. I even changed credentials to say include.

I am using expo and my terminal on Windows to run it without having to use android studio or xcode. I am not sure if that is a possible issue.

Any thoughts!

Thanks

Lion789
  • 4,402
  • 12
  • 58
  • 96

2 Answers2

2

react-native-keychain is safer than cookies!

Second, have you tried AsyncStorage? This is React Native built in "localStorage" in essence. I think it's what you're looking for.

// to set
AsyncStorage.setItem('@app:session', token);

// to get
AsyncStorage.getItem('@app:session').then(token => {
  // use token
});

If your setup looks like this, where you simply are sending the token value through as headers, you can store this information in whatever format is safest/most convenient.

In this example, auth could be either of these options fetched.

localStorage.set('token', 38573875ihdkhai)
createCookie('ppkcookie' 7asdfasdf);

export const userFetchRequest = () => (dispatch, getState) => {
  let {auth} = getState();
  return superagent.get(`${__API_URL__}/user/me`)
    .set('Authorization', `Bearer ${auth}`)
    .then(res => {
      dispatch(userSet(res.body));
      return res;
    });
};
Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
Gavin Thomas
  • 1,827
  • 2
  • 11
  • 17
  • Please see the comment I made below. Again I am using cookies with the website so I need to have cookies working :/ – Lion789 Dec 17 '17 at 23:58
  • No understood, and that is fine, but I was having trouble setting headers. In regards to code, look at the fetch I am calling above. How do I add a "Cookie" to the header for that? Not sure I understand this new code you posted? Thanks for your help! – Lion789 Dec 18 '17 at 05:53
1

You can use cookies or just store a token in a localStorage for the web app.

But for the React Native app usage of AsyncStorage would be the better solution.

About AsyncStorage:

AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.

On iOS, AsyncStorage is backed by native code that stores small values in a serialized dictionary and larger values in separate files. On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.

Also, AsyncStorage has quite simple API:

const TOKEN = "TOKEN";

// save token
AsyncStorage.setItem(TOKEN, token);

// get token
AsyncStorage.getItem(TOKEN).then(token => {
  // token value could be used
});

If you are bothering about AsyncStorage security you can find more information by the link.

Anton K
  • 102
  • 1
  • 8
  • 1
    The reason I was looking for cookies, was because I need to have the same token passed with every header when a request is made. Also, since the server is working with the website it looks for cookies from the website so figured I can keep the same call to check for the app as well... any ideas if I can at least send the token from async in the header as a cookie. Been having issues with that whole thing – Lion789 Dec 17 '17 at 23:55
  • Yes , if you post your code of how you set your headers I can tell for sure. But if you’re sending it as bearer auth you can easily use any sort of hashing, or special key phrase that you choose. In this case it will be whatever you create a set with async – Gavin Thomas Dec 18 '17 at 00:17
  • Maybe if you give a quick rundown of your architecture it can be more clear. But I’m assuming when a Web or mobile user pinfa your back end it sends a cookie (which is just a hash of numbers or letters in your case?)back in the headers. Regardless of the application you take the value of that cookie and set it into whatever method you choose. – Gavin Thomas Dec 18 '17 at 00:28
  • When you say you need cookies working, you must understand, a cookie is a method to store user information locally on their machine to make page reloads faster. All it is doing is storing information YOU as the developer put there. So I would ask you need "cookies" to authenticate a user correct? Well that "cookie" is (probably) just a hashed out string of numbers/characters/or letters. The way you are using cookies on your web app (probably), is storing the "cookie" (numbers/letters) (from the backend) to be used to auto authentic future requests. My point in all this, persistance. – Gavin Thomas Dec 18 '17 at 00:46
  • You can store the exact same numbers/letters/characters with local storage or Async, its just persisting that string in a different form. – Gavin Thomas Dec 18 '17 at 00:48