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
?
You need to wrap user. getIdToken() inside of firebase. auth(). onAuthStateChanged for user to be available.
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.
Generating Tokens You can generate tokens on the server by creating a Server Client and then using the Create Token method.
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.
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;
});
}
});
Just putting await
before will work too just like this:
await auth().currentUser.getIdToken();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With