React native set cookie on fetch/axios

Viewed 5450

I am trying to set the cookie on fetch or axios, I already checked the solutions posted on github or stackoverflow, but none of them are working now. I'm using Saml for authentication on my RN project.

So Here are stories:

on the first login, if the user clicks the start button, it calls the api of get profile info, if there is no cookie on header, it returns redirect url and also cookie(it's unauth cookie), and go to the url on the webview, after the user logins on the webview, then the original url(get profile api) is called on webview, after that, I'd grab the auth cookie using react-native-cookies library, and then set it on the header of fetch/axios. but it doesn't work.

export async function getMyProfile() {
  const cookies = await LocalStorage.getAuthCookies();
    await CookieManager.clearAll(true)
    const url = `${Config.API_URL}/profiles/authme`;
    let options = {
      method: 'GET',
      url: url,
      headers: {
        'Content-Type': 'application/json',
      },
      withCredentials: true
    };
    if (cookies) options.headers.Cookie = cookies.join(';')
    return axios(options)
    .then(res => {
      console.info('res', res);
      return res;
    }).catch(async (err) => {
      if (err.response) {
        if (err.response.status === 401) {
          const location = _.get(err, 'response.headers.location', null);
          const cookie = _.get(err, 'response.headers.set-cookie[0]', null);
          await LocalStorage.saveUnAuthCookie(cookie);
          return { location, cookie, isRedirect: true };
        }
      }
    });
}
1 Answers

You could use Axios interceptor.

  let cookie = null;

  const axiosObj = axios.create({
      baseURL: '',
      headers: {
        'Content-Type': 'application/json',
      },
      responseType: 'json',
      withCredentials: true, // enable use of cookies outside web browser
    });

    // this will check if cookies are there for every request and send request
    axiosObj.interceptors.request.use(async config => {
      cookie = await AsyncStorage.getItem('cookie');
      if (cookie) {
        config.headers.Cookie = cookie;
      }
      return config;
    });
Related