How to keep the user logged in with launchWebAuthFlow?

971 Views Asked by At

In my Chrome extension, I'm using launchWebAuthFlow to authenticate the user via their Google account:

function launchGoogleAuthFlow(interactive) {
  return new Promise((resolve, reject) => {
    const manifest = chrome.runtime.getManifest();
    const clientId = encodeURIComponent(manifest.oauth2.client_id);
    const scopes = encodeURIComponent(manifest.oauth2.scopes.join(' '));
    const redirectUri = encodeURIComponent('https://' + chrome.runtime.id + '.chromiumapp.org');

    const url = 'https://accounts.google.com/o/oauth2/auth' +
      '?client_id=' + clientId +
      '&response_type=id_token' +
      '&access_type=offline' +
      '&redirect_uri=' + redirectUri +
      '&scope=' + scopes

    chrome.identity.launchWebAuthFlow(
      {
        'url': url,
        'interactive': interactive
      },
      (redirectedTo) => {
        if (chrome.runtime.lastError) {
          console.log(chrome.runtime.lastError.message);
          resolve(null)
        }
        else {
          console.log(redirectedTo);
          console.log(JSON.stringify(redirectedTo));
          let idToken = redirectedTo.substring(redirectedTo.indexOf('id_token=') + 9)
          idToken = idToken.substring(0, idToken.indexOf('&'))
          resolve(idToken)
        }
      }
    )
  })
}

After the initial sign-in, I can use interactive: false to sign in the user again automatically. But after the browser was closed completely, they have to sign in interactively again. Do I have to implement the refresh token logic myself?

1

There are 1 best solutions below

0
Myunghoon Haru Lee On

That's what I did.

I stored the user's tokens in their browser (browser.storage.local or chrome.storage.local) upon a successful login.

Then, next time the LogIn button is clicked, it would check for the tokens (and their expiry) and open chrome.identity.launchWebAuthFlow conditionally