Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current users access token from Firebase in React Native

I am trying to get the Firebase authentication access token within a React Native application so that I can authenticate my API calls to a custom server. The Firebase documentation says I should get this token by using auth().currentUser.getIdToken(); however currentUser returns null.

I've tried to use getIdToken() in multiple areas of the application. I know the access token is generated as I can see it in the logs while using expo (user.stsTokenManager.accessToken).

Why is currentUser returning null and how can I get the accessToken?

like image 888
Edd Avatar asked Apr 02 '19 09:04

Edd


People also ask

How do I get the access token from Firebase React Native?

You need to wrap user. getIdToken() inside of firebase. auth(). onAuthStateChanged for user to be available.

How do I check my Firebase ID token?

To do so securely, after a successful sign-in, send the user's ID token to your server using HTTPS. Then, on the server, verify the integrity and authenticity of the ID token and retrieve the uid from it. You can use the uid transmitted in this way to securely identify the currently signed-in user on your server.

How do you get a token in React Native?

Generating Tokens You can generate tokens on the server by creating a Server Client and then using the Create Token method.

How do I get the access token in react?

Your access token While the user is logged in, their access token is available in your React application as Userfront. accessToken() . Your React application can send this as a Bearer token inside the Authorization header to your backend server.


2 Answers

You need to wrap user.getIdToken() inside of firebase.auth().onAuthStateChanged for user to be available. You can then use jwtToken in your header to authenticate your API calls. You need to import your Firebase configuration file for this to work.

let jwtToken = firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      user.getIdToken().then(function(idToken) {  // <------ Check this line
          alert(idToken); // It shows the Firebase token now
          return idToken;
      });
    }
  });
like image 73
Edd Avatar answered Sep 25 '22 14:09

Edd


Just putting await before will work too just like this:

await auth().currentUser.getIdToken();

like image 41
Bhavya Koshiya Avatar answered Sep 25 '22 14:09

Bhavya Koshiya