how to Get new access token and refresh token after 1 hour with firebase authentication

Viewed 480

after this i get a new access token but expires after 1 hour

const auth = getAuth();
signInWithPopup(auth, provider)
  .then((result) => {
    // This gives you a Google Access Token. You can use it to access the Google API.
    const credential = GoogleAuthProvider.credentialFromResult(result);
    const token = credential.accessToken;
    // The signed-in user info.
    const user = result.user;
    // ...
  }).catch((error) => {
    // Handle Errors here.
    const errorCode = error.code;
    const errorMessage = error.message;
    // The email of the user's account used.
    const email = error.email;
    // The AuthCredential type that was used.
    const credential = GoogleAuthProvider.credentialFromError(error);
    // ...
  });

How do I get the new access token without re-logging in?

1 Answers

A 'lazy' solution, I used for my non-commercial client app in Angular, is to automatically re-authenticate already logged in users via the redirect, when those hit an area of the app where an access token is required. Thus, you can retrieve fresh access token from the result of the redirect and without storing it in the browser's storage (safer). As long as a user remains authenticated with Google, you can retrieve the state and force through the redirect where user will not need to take any actions. The main downside, the loading of the resources becomes longer with an additional Google service redirect.

...
// where fireAuth is AngularFireAuth module
this.fireAuth.getRedirectResult().then(...)
...

private createProvider(): GoogleAuthProvider {
  const provider = new firebase.auth.GoogleAuthProvider
  provider.addScope(clientConfig.scope)
  return provider
}

public reauthenticate(): void {
  // where user$ is an equivalent to the Firebase user or authState object
  this.user$.subscribe(user => user.reauthenticateWithRedirect(this.createProvider())
  )
}

The more robust solution would entail usage of Google Identity SDK (GIS) and OAuth 2.0 for the web server apps (Google provides an example doing it with Flask here). I am not sure how it was always for Firebase, when it comes to managing scopes and access tokens for the Google APIs, but with the recent migration to the updated GIS, the access token can be retrieved only on an initial authentication. As per access token refresh, here is a section from the above link, that explains how you can do it without incrementally prompting a user for the permission. Shortly, with access_type set to offline in the initial authorization process.

Access tokens periodically expire and become invalid credentials for a related API request. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.

Related