0

I'm making an app using Expo that has session cookie authentication. The backend is express sessions.

When a user sucessfully signs in, I store the token that's given by the server in Async storage on the device. When the user logs out or checkAuth fails for some reason (for example if the session has expired) I clear the token from Async storage and set the state to not authenticated. All this works good and seems to be robust.

Now I have encountered what might be a problem. For all other requests that aren't related to logging in or checking auth, I also need to send the token to server for authorization. For example when logging out.

I use Axios and need a way to attach the token that's currently stored in Async storage to the request. I have a custom Axios instance that's used in all requests. I'm thinking I could attach the token through that instance? Something like this:

import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

const getStoredSessionID = async () => { // this function gets the auth token from storage
  try {
    const value = await AsyncStorage.getItem('local_sid');
    return value;
  } catch (e) {
    alert("Async storage error")
  }
};

const axiosInstance = axios.create({
    baseURL: 'http://192.168.0.6:3002',
    timeout: 4000,
    headers: {'Cookie': `user_sid=${getStoredSessionID}`}
  });
  export default axiosInstance;

Does the code above make sense at all? Or is there maybe a better way? Please let me know if this is vague or if more information is needed. BIG thanks for any input!

The code above did not work as intended.

  • 1
    Does this answer your question? [Attach Authorization header for all axios requests](https://stackoverflow.com/questions/43051291/attach-authorization-header-for-all-axios-requests) – user18309290 Aug 30 '23 at 15:20

1 Answers1

0

I would have used interceptors for this. Axios has a nice way of adding logic to requests (and responses). See here about interceptors

import axios from "axios";
import AsyncStorage from '@react-native-async-storage/async-storage';

const getStoredSessionID = async () => { // this function gets the auth token from storage
  try {
    const value = await AsyncStorage.getItem('local_sid');
    return value;
  } catch (e) {
    alert("Async storage error")
  }
};
    
const axiosInstance = axios.create({
    baseURL: 'http://192.168.0.6:3002',
    timeout: 4000,
    headers: {'Cookie': `user_sid=${getStoredSessionID}`}
  });

axiosInstance.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Cookie = `user_sid=${getStoredSessionID}`;
    return config;
});

Maybe consider adding validation to your stored session id, in case it could be tampered with...

Good luck

Lior Kupers
  • 528
  • 6
  • 18