Z0q
Z0q

Reputation: 1883

How to get the unique user ID in a chrome extension using OAuth?

I am using the identity permission in my manifest file and in my JavaScript code I use chrome.identity.getAuthToken({ 'interactive': true }, function( token ) to get the use identification token.

How do I get the unique user ID or e-mail address? Preferrably without adding new permissions.

Upvotes: 5

Views: 6564

Answers (2)

rhashimoto
rhashimoto

Reputation: 15841

You can use chrome.identity.getProfileUserInfo() to get both the email address and a unique id. You will need to add the identity.email permission (in addition to identity). It does not require an OAuth2 token (or even a network connection).

Here is a minimal extension that prints this information to the console of a background page:

manifest.json

{
  "manifest_version" : 2,

  "name" : "Identity Test",
  "version" : "0.1",

  "background": {
    "scripts": ["background.js"]
  },

  "permissions": [
    "identity",
    "identity.email"
  ]
}

background.js

chrome.identity.getProfileUserInfo(function(userInfo) {
  console.log(JSON.stringify(userInfo));
});

You could instead get user info by calling the Google API with the OAuth2 token. I believe you will need to set both the profile and email scopes. If you use the Google API Client library, you can call gapi.client.oauth2.userinfo.get(). This more strictly satisfies the letter of your question, which specifies using OAuth and prefers not adding permissions, but I would guess that chrome.identity.getProfileUserInfo() is what you're really looking for.

Upvotes: 10

Iván Nokonoko
Iván Nokonoko

Reputation: 5118

Without additional permissions, it will depend on the oauth2 scopes you declared in your manifest.json file.

For example, if you declared any Google Drive scope, you can use Google Drive's About GET method (see here) to retrieve the user's id and e-mail, among other data.

Upvotes: 1

Related Questions