chrome.identity User Authentication in a Chrome Extension

You don’t have to upload an extension to the Chrome Web Store in order to use the chrome.identity API. It suffices to have a valid extension ID. The easiest way to get started is to copy the 32-character extension ID from chrome://extensions/ to your project’s credentials section at the API console see screenshot below.
Though if you ever want to publish the extension or use it in a different profile or computer, then you’d better choose an extension ID that you control. This can be done by setting the "key" key in the manifest file. See Obtaining Chrome Extension ID for development for a detailed answer on generating these keys.

For example, try out the following extension, using a key that I just generated. It will print your user info in a dialog.

manifest.json

{
    "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0W0/YVPvLrj2cWBOXfPBBYwPp56R+OJb9QLudyMpigF+V4DFV0NEUnbo9iA6m+7cVPiD6YbhbIaiAoHSdtqEKwaYvrEJRGuGsLjDq+RMwG2x+FcGIsO4ny0BuZaZ/Q2+DaL33NBUl2h9dIi1xa0Suq6qpoJ4yykTu9y7Q6rB9ulJze6DiZL7LWU5NzHCEWt21zAhpLZOqvYY8wzY69pMf+P0+uOLuy87x84rvCRNegbSmEYLC5f4y6ikjVnFUxJBxMlpMg3bByxbrLVBFPuHj4khkr6adUXgks2vBBHFcrRh5EYXopI+PLwUJPfFtzyN8+L7swen9kcK8gXMwX28KwIDAQAB",
    "name": "Identity test",
    "version": "1",
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"]
    },  
    "permissions": [
        "identity"
    ],  
    "oauth2": {
        "client_id": "1014705257182-52dddl9dbiec2ln22stokphlaq0v7gor.apps.googleusercontent.com",
        "scopes": ["profile"]   
    }   
}

background.js

chrome.identity.getAuthToken({
    interactive: true
}, function(token) {
    if (chrome.runtime.lastError) {
        alert(chrome.runtime.lastError.message);
        return;
    }
    var x = new XMLHttpRequest();
    x.open('GET', 'https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token=' + token);
    x.onload = function() {
        alert(x.response);
    };
    x.send();
});

Leave a Comment