RRR uzumaki
RRR uzumaki

Reputation: 1328

Most ideal way to call firebase getIdToken

i am implementing user authentication with the help of firebase in my React project. So, I am confused over something.

I am verifying the user from firebase and then getting a token on frontend which is sent to backend via headers and verfied there once.

I read the docs and came to know that firebase token gets expired after 1 hr by default so we have to use "getIdToken" like

 firebase.auth().onAuthStateChanged(async user => {
      if (user) {
        console.log(user, 'user123 inside firebaseAuth')
        const token = await user.getIdToken()

        Cookies.set('my_token', token, { domain: domain })
      }
    })

but how do i manage this function , do i have to call it everytime the component updates or everytime before hitting api or first time the component renders ?

The thing is i do not want this token to get expire until the user logs out himself / herself even if he is in a different component and sitting ideal for too long.

Upvotes: 2

Views: 1660

Answers (2)

Edudate Academy
Edudate Academy

Reputation: 1

A practical way to do this is through a JWT interceptor, First you declare an interreceptor as an injectable service

@Injectable()
export class AuthJWTInterceptor implements HttpInterceptor {
constructor(private authService: AuthService,
public auth: AngularFireAuth) { super(); }
jwt(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return this.auth.idToken
  .pipe(
    take(1),
    switchMap((token: any) => {
      if (token) request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
      return next.handle(request)
}))

override intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return this.jwt(request, next);

} }

Then on each HTTP request, this interceptor detects the Idtoken and places it on the header. Take a peek on this Angular Interceptors

Upvotes: 0

Dharmaraj
Dharmaraj

Reputation: 50850

You can get the Firebase ID Token every time you are making an API call to your server:

async function callAPI() {
  const user = firebase.auth().currentUser
  if (user) {
    const token = await user.getIdToken()
    const res = await fetch("url", {
      headers: {authorization: `Bearer ${token}`}
    })
  } else {
    console.log("No user is logged in")
  }
}

You could get the ID token once when the component mounts but then you'll have to deal with onIdTokenChanged to keep it updated in your state. Using the method above you'll get a valid token always.

Upvotes: 4

Related Questions