1
votes

I implemented Firebase Phone Auth for SignIn in my ReactNative project. Now I want to use this JWTToken to be passed to the API calls that I make to my server.

And at the server side, I would be validating the token which was passed through the API calls and respond with the proper response. My question is, how can I pass this token in the API calls that I make to my server?

  1. I can store the token (within my first loading screen of the app, where it authenticates the User) in the localStorage and fetch it later in any of my screens to make the API calls
  2. I can access the Token directly my importing the firebase package in each and every screen (from which am planning to do the API calls) like this: https://rnfirebase.io/reference/auth/idtokenresult and pass it in the API calls

But I was thinking about storing the Token (fetched during the loading screen) in a global variable inside my ReactNative project and that can be accessed from any screens. But I couldn't find how this can be done? Or which one would be the more appropriate way to do this?


EDIT:

This is how am getting the Token :

  auth().onIdTokenChanged(function(user) {
    if (user) {
      
      user.getIdToken().then( token => {
        console.log( token )
      });

    }
  });
1

1 Answers

2
votes

Storing the token in local storage is not going to work out well for you in the long run. ID tokens expire after 1 hour, and will not successfully verify on the server after that.

Each individual page should set up an ID token listener so it can use the most fresh token provided by the Firebase Auth SDK. The SDK will automatically refresh it and provide you with the latest token in the callback. Every time the token changes, you should use that value in your API calls. Use onIdTokenChanged():

firebase.auth().onIdTokenChanged(function(user) {
  if (user) {
    // User is signed in or token was refreshed.
  }
});