Getting 401 from Google user info endpoint

1.9k Views Asked by At

I am trying to get users to authorize the app for "offline" access.

I have the token url as "https://oauth2.googleapis.com/token". I hit that with params such as the one-time code, client_id, client_secret, scopes etc to get a response containing tokens. It looks like the below:

{
  access_token: ...,
  expires_in: 3599,
  refresh_token: ...,
  scope: ...,
  token_type: 'Bearer'
}

I take the access_token value from the above response and try to use it to pull userInfo from "https://www.googleapis.com/oauth2/v1/userinfo?alt=json" and it is always returning 401.

I did it with code and curl, trying to pass the token in the authorization header as

const headers = {
  Authorization: `Bearer ${accessToken}`
};
const userInfo = await fetch('https://www.googleapis.com/oauth2/v1/userinfo?alt=json',{headers});

and also tried to add the access_token to the query string, as well as executing against newer endpoints such as https://www.googleapis.com/oauth2/v2/userinfo?alt=json and https://www.googleapis.com/oauth2/v4/userinfo?alt=json.

I am always getting 401. The message is: Request is missing required authentication credentials...

What should I be doing instead?

1

There are 1 best solutions below

0
On

The userinfo end point is a HTTP GET call you can string the access token as a query parameter.

https://openidconnect.googleapis.com/v1/userinfo?access_token=ya29.a0AfH6SMDfRQFdEOxq97LXqUa1jwdtRLSD2l_hiLFeaWYXRBB6gIkh7XHko75xj70uPnuOppKtf0c 

Response

{
  "sub": "1172004755326746",
  "name": "Linda Lawton",
  "given_name": "Linda",
  "family_name": "Lawton",
  "picture": "https://lh3.googleusercontent.com/a-/AOh14GhroCYJp2P9xeYeYk1npchBPK-zbtTxzNQo0WAHI20\u003ds96-c",
  "locale": "en"
}

BTW you may want to consider using the people api in stead its much more stable then the userinfo endpoint.