Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get firebase token with angular, with firebase authentication sdk?

i am trying to create project in angular, i am using firebase sdk to get token. i’m following the documentation and i’m using the "firebase" package: "^9.17.2",
I can authenticate, but I can’t extract the token from the response.

this is the code i use:

`signInWithEmailAndPassword(auth, "email", "pwd")
      .then((userCredential) => {
        return userCredential;
        // Signed in 
        const user = userCredential.user;
        var token = user.getIdTokenResult(true);
        console.log(token);
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
      });`

i can’t extract the token even though user has all the fields inside. the goal is to store the token into the local storage and also the refresh token. the next step would be to create a function to refresh the token (but i can’t even get them).
Thanks to all for any possible help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The method getIdTokenResult() returns a Promise<IdTokenResult>, therefore you need to use await/async to be able to wait for the promise to finish and return the result:

signInWithEmailAndPassword(auth, "email", "pwd")
      .then(async (userCredential) => {
        return userCredential;
        // Signed in 
        const user = userCredential.user;
        var idTokenResult = await user.getIdTokenResult(true);
        console.log(idTokenResult.token);
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
      });

The IdTokenResult has the property token which then you can access after the promise returns the result.

Take into account also, that you need a valid email and password to be passed as an argument to signInWithEmailAndPassword

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading