I am trying to use firebase phone authentication in my ionic angular app. I am loving in to the app using firebase authentication at the beginning. After that, I do not want Customer need to login again and again. So I am checking if the user already logged in then get the new idToken for the customer. I need to pass the idToken as “FireBaseIdToken” in the backend service headers. printIdToken() function is printing the new toke perfectly. When I am trying to use callIdToken(), it is calling asynchronous way. I want it to wait for promis to complete then the returned value should be added in the header. I tried to use await inside callIdToken() , but it is not waiting for the promise. It need to wait for promise.
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http'
import { Auth, onAuthStateChanged } from '@angular/fire/auth';
@Injectable({
providedIn: 'root'
})
export class AuthinterceptorService implements HttpInterceptor {
constructor(private auth: Auth) { }
intercept(req, next) {
console.log("Request URL:: : " + req.url);
let tokenizedReq;
if (req.url.includes("/auth/customer/")) {
console.log(" callIdToken start");
//this.printIdToken();
const idToken = this.callIdToken();
console.log("IdToken :",idToken);
console.log("callIdToken Completed");
tokenizedReq = req.clone(
{
headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('actualToken'))
.set('FireBaseIdToken', 'FireBase ' + idToken)
}
)
} else {
tokenizedReq = req.clone(
{
headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('actualToken'))
}
)
}
return next.handle(tokenizedReq)
}
async callIdToken() {
onAuthStateChanged(this.auth, (user) => {
if (user) {
return this.auth.currentUser.getIdToken();
} else {
return null;
}
});
}
async printIdToken()
{
console.log("Inside Service4");
onAuthStateChanged(this.auth, (user) => {
if (user) {
this.auth.currentUser.getIdToken()
.then((confirmationResult) => {
console.log(confirmationResult);
}).catch((error) => {
console.error("Error :", error);
});
} else {
console.log("logged out");
// User is signed out
// ...
}
});
}
}
USING await
=============
` callIdToken(){
onAuthStateChanged(this.auth, (user) => {
if (user) {
console.log("Testing");
const token = async () =>{
console.log("In side Testing");
return await this.auth.currentUser.getIdToken();
}
console.log("Testing",token);
}});
}
Himadri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.