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
>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