Pass firebase access token to backend in axios interceptor

Viewed 755

I need some help understanding how to pass in a firebase bearer/jwt token with my api requests to the backend.

I am using axios and using an interceptor to set up the bearer token similar to this

 axios.interceptors.request.use(
config => {
  const userData = store.getters['firebaseAuth/user']
  
  if (userData && userData.accessToken) {
    config.headers['Authorization'] = 'Bearer ' + userData.accessToken
  }

In all the examples for firebase auth, I have seen that the way to get the jwt token is like so:

 firebase
  .auth()
  .currentUser.getIdToken(/* forceRefresh */ true)
  .then(idToken => {

Would it be good practice to run this in my interceptor to obtain the access token?..

Feels like an unnecessary extra api call to firebase servers for every request made to my backend server.

Also I have trouble understanding why I should even use this firebase method (getIdToken) when the token is available as a property from the user object. It has a strange name "za" which i think is deliberate from firebase, and nowhere mentions to use this to get the id/bearer/access token.

 firebase.auth().onAuthStateChanged(user => {
  if (user) {
//user.za  id the id/bearer/access token

My initial thought was to just store user.za in localstorage then fetch it from local storage in the interceptor.

1 Answers

I'm not sure if it is the best way, but I ended up using the Firebase SDK methods in my interceptor directly. My understanding of the getIdToken API is that the promise returns a cached JWT, unless it is expired, in which case it will return a fresh one. I made the interceptor function async, and use await to synchronously request the token.

axios.interceptors.request.use(
async function (request) {
  const user = currentUser();

  if (user) {
    try {
      const token = await user.getIdToken(false); // Force refresh is false
      request.headers["Authorization"] = "Bearer " + token;
    } catch (error) {
      console.log("Error obtaining auth token in interceptor, ", error);
    }
  }

  return request;
},...
Related