skip to Main Content

I have made a Chrome extension that successfully accesses the Google Drive API. It does so by employing access tokens like so…

chrome.identity.getAuthToken({ interactive: true }, (accessToken) => {
    sendResponse({ type: MESSAGE_PROTOCOL.AUTH_RESPONSE, accessToken });

…however, when I try and run the code on other Chrome-based browsers like Edge it appears that chrome.identity.getAuthToken is not available. After much Googling it seems that there is an alternative (involving launchWebAuthFlow) but I can not find a complete worked example, only little snippets and clues which I am not expert enough to convert into a solution. Surely there must be a complete example somewhere.

A worked example for a different Google API would probably be fine too.

EDIT: I just found this question which is probably pretty close to what I am after though so far I have failed to get any of the answers to work. I notice that the top voted answer to that question was for manifest v2 and I’m not sure whether the answer will be valid for v3. Can anyone confirm?

EDIT: Just to be clear, I don’t have my own server, I want the whole process to be handled by the extension itself.

EDIT: If anyone knows of an existing extension that accesses a Google API, can work on Edge, uses manifest v3, is not compressed/obfuscated and does not rely on its own server then I could examine the code myself and that should do the trick.

2

Answers


  1. In manifest v3, you need to use a different approach to authenticate with the Google Drive API. Instead of using chrome.identity.getAuthToken, you can use the chrome.identity.getRedirectURL method in combination with a redirect flow.

    Here’s an example of how you can authenticate with the Google Drive API in a Chrome extension using manifest v3:

    1. Update your manifest.json file with the necessary permissions and the redirect URL:
    {
      "manifest_version": 3,
      "name": "Your Extension",
      "version": "1.0",
      "permissions": [
        "identity",
        "https://www.googleapis.com/*"
      ],
      "oauth2": {
        "client_id": "YOUR_CLIENT_ID",
        "scopes": [
          "https://www.googleapis.com/auth/drive"
        ],
        "redirect_uri": "YOUR_REDIRECT_URI"
      },
      "background": {
        "service_worker": "background.js"
      }
    }
    
    1. Create a background.js file with the following code:
    chrome.runtime.onInstalled.addListener(() => {
      // Open the authorization URL in a new tab
      chrome.identity.launchWebAuthFlow({
        url: 'https://accounts.google.com/o/oauth2/auth' +
          '?client_id=YOUR_CLIENT_ID' +
          '&redirect_uri=' + encodeURIComponent(chrome.identity.getRedirectURL()) +
          '&response_type=token' +
          '&scope=https://www.googleapis.com/auth/drive',
        interactive: true
      }, (redirectUrl) => {
        // Parse the redirected URL to extract the access token
        const accessToken = redirectUrl.match(/[#?](?:access_token)=([^&]+)/)[1];
        // Use the access token as needed
        console.log(accessToken);
      });
    });
    

    With this setup, when the extension is installed or updated, it will open the authorization URL in a new tab and prompt the user for authentication. After authentication, the extension will receive the access token in the redirect URL, which you can then use for subsequent API calls.

    Login or Signup to reply.
  2. I am getting "Error 400: redirect_uri_mismatch".
    I have made a file oauth2callback.html which I put in the root directory of my extension. The manifest includes "redirect_uri": "oauth2callback.html" immediately after the scopes list.

    That error should mean there is a mismatch between the redirect URI specified in the OAuth2 request and the one registered in the Google Cloud Console for the OAuth2 client ID.
    See "Obtaining OAuth 2.0 access tokens / Redirect to Google’s OAuth 2.0 server".

    Go to the Google Cloud Console, navigate to the Credentials page. Under the "Authorized redirect URIs" section, make sure to add the exact redirect URI that your extension is using. In this case, it should be the URI to the oauth2callback.html file in your extension, which would be formed like: https://<your-extension-id>.chromiumapp.org/oauth2callback.html.

    In the manifest.json file, the redirect_uri field should be set to the correct redirect URI, with the format shown above. Make sure the redirect URI in your manifest.json file and the one in the background.js file match exactly with the one registered in the Google Cloud Console.

    "oauth2": {
        ...
        "redirect_uri": "https://<your-extension-id>.chromiumapp.org/oauth2callback.html"
    }
    

    When constructing the authorization URL in your background.js file, use the chrome.identity.getRedirectURL method to obtain the correct redirect URI for your extension. Replace 'YOUR_REDIRECT_URI' with chrome.identity.getRedirectURL('oauth2callback.html') in the authorization URL.

    url: 'https://accounts.google.com/o/oauth2/auth' +
      '?client_id=YOUR_CLIENT_ID' +
      '&redirect_uri=' + encodeURIComponent(chrome.identity.getRedirectURL('oauth2callback.html')) +
      '&response_type=token' +
      '&scope=https://www.googleapis.com/auth/drive',
    

    My software is a chrome extension.

    Chrome Extensions have a different flow for handling OAuth 2.0 authentication, and they do not require manual configuration of redirect URIs in the Google Cloud Console as web applications do. The redirect URI for a Chrome extension is derived from the extension’s ID and is automatically constructed as https://<extension-id>.chromiumapp.org/.

    In the background.js script, the redirect_uri parameter should be obtained using chrome.identity.getRedirectURL() method without any arguments:

    '&redirect_uri=' + encodeURIComponent(chrome.identity.getRedirectURL())
    

    That will automatically generate the correct redirect URI based on the extension’s ID.

    Then make sure the client_id specified in the manifest.json file and the background.js script corresponds to the OAuth 2.0 client ID generated in the Google Cloud Console for the Chrome Extension.

    And check that the permissions in the manifest.json file include "identity" and the correct API scope for Google Drive:

    "permissions": [
          "identity",
          "https://www.googleapis.com/*"
    ],
    "oauth2": {
          "client_id": "YOUR_CLIENT_ID",
          "scopes": [
             "https://www.googleapis.com/auth/drive.file"
          ]
    }
    

    Just in case, check that the OAuth consent screen configuration in the Google Cloud Console is correctly set up, including the application name, support email, and other necessary details.

    Load the extension in Chrome (or a Chromium-based browser), check that there are errors in the console, and test the OAuth 2.0 flow again.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search