> [!WARNING]
> **Warning:** You're viewing the deprecated Manifest V2 version of this article. See [Manifest V3 - OAuth2: Authenticate users with Google](https://developer.chrome.com/docs/extensions/how-to/integrate/oauth.md.txt) for the MV3 equivalent. The Chrome Web Store no longer accepts Manifest V2 extensions. Follow the [Manifest V3 Migration guide](https://developer.chrome.com/docs/extensions/develop/migrate.md.txt) to convert your extension to Manifest V3.

[OAuth2](https://oauth.net/2/) is the industry-standard protocol for authorization. It provides a mechanism for users
to grant web and desktop applications access to private information without sharing their username,
password and other private credentials.

This tutorial builds an extension that accesses a user's Google contacts using the [Google People
API](https://developers.google.com/people/) and the [Chrome Identity API](https://developers.google.com/identity). Because extensions don't load over HTTPS, can't perform
redirects or set cookies, they rely on the Chrome Identity API to use OAuth2.

## Get started

Begin by creating a directory and the following starter files.

The full, completed extension can be downloaded [here](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/examples/tutorials/oauth_tutorial_complete.zip).

### manifest.json

Add the manifest by creating a file called `manifest.json` and include the following code. Or
download the file [here](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/examples/tutorials/oauth_starter/manifest.json).

```json
{
  "name": "OAuth Tutorial FriendBlock",
  "version": "1.0",
  "description": "Uses OAuth to connect to Google's People API and display contacts photos.",
  "manifest_version": 2,
  "browser_action": {
    "default_title": "FriendBlock, friends face's in a block."
  },
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": false
  }
}
```

### background.js

Add the background script by creating a file called `background.js` and include the following code.
Or download the file [here](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/examples/tutorials/oauth_starter/background.js).

```javascript
chrome.browserAction.onClicked.addListener(function() {
  chrome.tabs.create({url: 'index.html'});
});
```

### index.html

Add an HTML file called `index.html` and include the following code. Or download the file [here](https://developer.chrome.com/docs/extensions/mv2/tutorials/oauth/examples/tutorials/oauth_starter).

```html
<html>
  <head>
    <title>FriendBlock</title>
    <style>
      button {
        padding: 10px;
        background-color: #3C79F8;
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <button>FriendBlock Contacts</button>
    <div id="friendDiv"></div>
  </body>
</html>
```

## Upload to the developer dashboard

Package the extension directory into a `.zip` file and upload it to the [Chrome Developer
Dashboard](https://chrome.google.com/webstore/developer/dashboard) without publishing it:

1. At the Developer Dashboard, click **Add new item**.
2. Click **Choose file** and select the `.zip` extension directory and upload it.
3. Without filling in additional fields, select **Save Draft and return to dashboard**.

Find the extension under **Your Listings** and click on **more info** . From the popup, copy the
public key and add it to the manifest inside the unzipped directory under the [`"key"`](https://developer.chrome.com/docs/extensions/mv2/manifest/key.md.txt) field.

```json
{
  "name": "OAuth Tutorial FriendBlock",
...
  "key": "ThisKeyIsGoingToBeVeryLong/go8G...AQAB"
}
```

## 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 matches in all places](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/image/the-id-the-extension-mat-e165db8cf613d.png)

The extension will maintain the same ID by including the `"key"` field in the manifest. Preserving a
single ID is essential for API registration.

## Create OAuth client ID

Navigate to the [Google API console](https://console.developers.google.com/apis) and create a new project. Once ready, select
**Credentials** in the sidebar, click **Create credentials** and choose **OAuth client ID**.

![Create credentials for extension](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/image/create-credentials-exten-222dca9a3dc93.png)

On the Create client ID page, select **Chrome App**. Fill out the name of the extension and place
the extension ID at the end of the URL in the Application ID field.

![Fill out extension information](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/image/fill-extension-informati-bf1f3148befb6.png)

Finish by clicking create. The console will provide an OAuth client ID.

## Register OAuth in manifest

Include the `"oauth2"` field in the extension manifest. Place the generated OAuth client ID under
`"client_id"`. Include an empty string in `"scopes"` for now.

```json
{
  "name": "OAuth Tutorial FriendBlock",
  ...
  "oauth2": {
    "client_id": "yourExtensionOAuthClientIDWillGoHere.apps.googleusercontent.com",
    "scopes":[""]
  },
  ...
}
```

## Initiate first OAuth flow

Register the [`identity`](https://developers.google.com/identity) permission in the manifest.

```json
{
  "name": "OAuth Tutorial FriendBlock",
  ...
  "permissions": [
    "identity"
  ],
  ...
}
```

Create a file to manage the OAuth flow called `oauth.js` and include the following code. Or download
it [here](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/examples/tutorials/oauth_starter/oauth.js).

```javascript
window.onload = function() {
  document.querySelector('button').addEventListener('click', function() {
    chrome.identity.getAuthToken({interactive: true}, function(token) {
      console.log(token);
    });
  });
};
```

Place a script tag for `oauth.js` in the head of `index.html`.

```html
...
  <head>
    <title>FriendBlock</title>
    ...
    <script type="text/javascript" src="oauth.js"></script>
  </head>
...
```

Reload the extension and click on the browser icon to open `index.html`. Open the console and click
on the "FriendBlock Contacts" button. An OAuth token will appear in the console.

![View the token in the console](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/image/view-token-the-console-9ff1d02a1d9fc.png)

## Enable the Google People API

Return to the Google API console and select **Library** from the sidebar. Search for "Google People
API", click on the correct result and enable it.

![Enable the People API](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/image/enable-people-api-f571e180a64db.png)

Add the [Google People API](https://developers.google.com/people/) client library to `"scopes"` in the extension manifest.

```json
{
  "name": "OAuth Tutorial FriendBlock",
  ...
  "oauth2": {
    "client_id": "yourExtensionOAuthClientIDWillGoHere.apps.googleusercontent.com",
    "scopes": [
      "https://www.googleapis.com/auth/contacts.readonly"
    ]
  },
  ...
}
```

Return to the Google API console and navigate back to credentials. Click "Create credentials" and
select "API key" from the dropdown.

![Create People API credentials](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/image/create-api-credentials-630ceea8e28fb.png)

Keep the generated API key for later use.

## Create first API request

Now that the extension has proper permissions, credentials, and can authorize a Google user, it can
request data through the People API. Update the code in `oauth.js` to match below.

```javascript
window.onload = function() {
  document.querySelector('button').addEventListener('click', function() {
    chrome.identity.getAuthToken({interactive: true}, function(token) {
      let init = {
        method: 'GET',
        async: true,
        headers: {
          Authorization: 'Bearer ' + token,
          'Content-Type': 'application/json'
        },
        'contentType': 'json'
      };
      fetch(
          'https://people.googleapis.com/v1/contactGroups/all?maxMembers=20&key=API_KEY',
          init)
          .then((response) => response.json())
          .then(function(data) {
            console.log(data)
          });
    });
  });
};
```

Replace `API_KEY` with the API key generated from the Google API console. The extension
should log a JSON object that includes an array of `people/account_id`s under the
`memberResourceNames` field.

## Block faces

Now that the extension is returning a list of the user's contacts, it can make additional requests
to [retrieve those contact's profiles and information](https://developers.google.com/people/v1/read-people) . The extension will use the
`memberResourceNames` to retrieve the photo information of user contacts. Update `oauth.js` to
include the following code.

    window.onload = function() {
      document.querySelector('button').addEventListener('click', function() {
        chrome.identity.getAuthToken({interactive: true}, function(token) {
          let init = {
            method: 'GET',
            async: true,
            headers: {
              Authorization: 'Bearer ' + token,
              'Content-Type': 'application/json'
            },
            'contentType': 'json'
          };
          fetch(
              'https://people.googleapis.com/v1/contactGroups/all?maxMembers=20&key=<API_Key_Here>',
              init)
              .then((response) => response.json())
              .then(function(data) {
                let photoDiv = document.querySelector('#friendDiv');
                let returnedContacts = data.memberResourceNames;
                for (let i = 0; i < returnedContacts.length; i++) {
                  fetch(
                      'https://people.googleapis.com/v1/' + returnedContacts[i] +
                          '?personFields=photos&key=API_KEY',
                      init)
                      .then((response) => response.json())
                      .then(function(data) {
                        let profileImg = document.createElement('img');
                        profileImg.src = data.photos[0].url;
                        photoDiv.appendChild(profileImg);
                      });
                };
              });
        });
      });
    };

Reload and return to the extension. Click the FriendBlock button and ta-da! Enjoy contact's faces in
a block.

![Contact faces in a block](https://developer.chrome.com/static/docs/extensions/mv2/tutorials/oauth/image/contact-faces-a-block-f8727dd16a64f.png)