Identifying the User

Published on Updated on

Supporting Google account sign-in can help provide a better user experience. Users of the Chrome Web Store are likely to be logged in to their Google account already, so they won't have to set up and remember yet another username and password.

This tutorial builds an extension using the Google OAuth2/OpenID endpoint and the Chrome Identity API. When the user clicks the action, the extension will launch a consent screen. After the user signs in to their Google account, the background will log their information in the console.

To identify the user with Google OAuth2/OpenId, follow these steps:

  1. Create your extension files.
  2. Keep a consistent extension ID.
  3. Get the OAuth client ID.
  4. Launch the Authorization flow.
  5. View the user information.

We'll explain each step below.

Create your extension files

Begin by creating a directory and the following starter files.

manifest.json

Add the manifest by creating a file called manifest.json and include the following code:

{
"name": "Google OpenID Connect Example",
"version": "1.0",
"description": "Use OpenID Connect to identify the user",
"manifest_version": 3,
"action": {
"default_title": "Sign In with Google Accounts"
},
"background": {
"service_worker": "background.js"
}
}

background.js

Add the background service worker by creating a file called background.js. Include the following code:

// background.js

chrome.action.onClicked.addListener(function() {
console.log('action clicked');
});

Keeping a consistent extension ID

Preserving a single ID is essential during development. To keep a consistent ID, follow these steps:

Upload extension to the developer dashboard

Package the extension directory into a .zip file and upload it to the Chrome Developer Dashboard without publishing it:

  1. On the Developer Dashboard, click Add new item.
  2. Click Browse files, select the extension's zip file, and upload it.
  3. Go to the Package tab and click View public key.
Developer Dashboard Package tab

When the popup is open, follow these steps:

  1. Copy the code in between -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY-----.
  2. Remove the newlines in order to make it a single line of text.
Public key popup

Add the code to the manifest.json under the "key" field. This way the extension will use the same ID.

{ // manifest.json 
"manifest_version": 3,
...
"key": "ThisKeyIsGoingToBeVeryLong/go8GGC2u3UD9WI3MkmBgyiDPP2OreImEQhPvwpliioUMJmERZK3zPAx72z8MDvGp7Fx7ZlzuZpL4yyp4zXBI+MUhFGoqEh32oYnm4qkS4JpjWva5Ktn4YpAWxd4pSCVs8I4MZms20+yx5OlnlmWQEwQiiIwPPwG1e1jRw0Ak5duPpE3uysVGZXkGhC5FyOFM+oVXwc1kMqrrKnQiMJ3lgh59LjkX4z1cDNX3MomyUMJ+I+DaWC2VdHggB74BNANSd+zkPQeNKg3o7FetlDJya1bk8ofdNBARxHFMBtMXu/ONfCT3Q2kCY9gZDRktmNRiHG/1cXhkIcN1RWrbsCkwIDAQAB",
}

Compare IDs

Open the Extensions Management page at chrome://extensions, ensure Developer mode is enabled, and upload the unpackaged extension directory. Compare the extension ID on the extensions management page to the Item ID in the Developer Dashboard. They should match.

The ID of the extension match

Get the OAuth client ID

Navigate to the Google API Console and create a new project. To get a OAuth client ID, follow these steps:

1. Customize the consent screen and select scope.

  • Click the OAuth consent screen menu item.
  • Fill out the required consent screen information.
  • Add the openid scope.
  • Add Test users.
  • Click Save > Continue.

2. Create credentials.

  • Click the Credentials menu item.
  • Click Create new credentials > Auth Client ID.
  • Select Application type Web application.
  • Enter the Name of the OAuth2 client
  • Add https://YOUR_EXTENSION_ID.chromiumapp.org/ as the Authorized redirect URI.
    • Replace YOUR_EXTENSION_ID with your extension's ID.
  • Finish by clicking Create.

The console will provide an OAuth client ID. Keep this ID for later use.

Launch the Authorization flow

Request the "identity" permission

To use the Chrome Identity API, declare the "identity" permission in the manifest.json.

{
"name": "Google OpenID Connect example",
...
"permissions": [
"identity"
],
...
}

Construct the authorization URL

Before the extension can make a request to Google’s OAuth2 endpoint using the Identity API, you need to construct an authorization URL. It must contain several request parameters including the client ID and redirect URI. In addition to the openid scope, you can request profile information and/or email. Update background.js to match the following code:

// background.js

let clientId = 'CLIENT_ID'
let redirectUri = `https://${chrome.runtime.id}.chromiumapp.org/`
let nonce = Math.random().toString(36).substring(2, 15)

chrome.action.onClicked.addListener(function() {
const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');

authUrl.searchParams.set('client_id', clientId);
authUrl.searchParams.set('response_type', 'id_token');
authUrl.searchParams.set('redirect_uri', redirectUri);
// Add the OpenID scope. Scopes allow you to access the user’s information.
authUrl.searchParams.set('scope', 'openid profile email');
authUrl.searchParams.set('nonce', nonce);
// Show the consent screen after login.
authUrl.searchParams.set('prompt', 'consent');
});

Replace CLIENT_ID with the API key generated from the Google console.

Retrieve a redirect URL

Now that the extension has the client ID, redirect URI, and OAuth URL, it can initiate Google's authentication flow. Call identity.launchWebAuthFlow() to launch the web auth flow and retrieve a redirect URL.

The redirect URL contains a JSON Web Token (JWT) that identifies the user. To view the requested user identity information, you'll need to parse the JWT into a plain JavaScript object. Update background.js to match the following code:

// background.js

...

chrome.action.onClicked.addListener(function() {

...

chrome.identity.launchWebAuthFlow(
{
url: authUrl.href,
interactive: true,
},
(redirectUrl) => {
if (redirectUrl) {
// The ID token is in the URL hash
const urlHash = redirectUrl.split('#')[1];
const params = new URLSearchParams(urlHash);
const jwt = params.get('id_token');

// Parse the JSON Web Token
const base64Url = jwt.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
const token = JSON.parse(atob(base64));

console.log('token', token);
}
},
);
});

The above code is not production ready. We strongly encourage validating and decoding the JWT before the information it contains is trusted. For more information, see how to handle credential responses.

View the user information

Reload and return to the extension. Click the extension action button to start the web authentication flow. Sign in with your Google Account, then press Enter.

ALT_TEXT_HERE

Go to the extension management page. Select the service worker blue link next to Inspect views. The extension should log the token containing the user information.

ALT_TEXT_HERE

Additional resources

Updated on Improve article

We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.