0
votes

When making requests to the Google OAuth2 API according to their documentation/guide, I keep getting 401 Unauthorized responses from https://accounts.google.com/oauth2/v4/token even though I swear I'm giving all the required fields:

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
User-Agent: curl/7.47.0
Accept: */*
Content-Length: 311
Content-Type: application/x-www-form-urlencoded

client_id=REDACTED
&client_secret=REDACTED
&code=REDACTED
&grant_type=authorization_code
&redirect_uri=https%3A%2F%2Flocalhost%2Fsso%3Fredirect%3D%252F

Response:

HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Vary: X-Origin
Vary: Referer
Date: Wed, 03 Jul 2019 16:14:15 GMT
Server: scaffolding on HTTPServer2
Cache-Control: private
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Alt-Svc: quic=":443"; ma=2592000; v="46,43,39"
Accept-Ranges: none
Vary: Origin,Accept-Encoding
Transfer-Encoding: chunked

{
  "error": "invalid_client",
  "error_description": "Unauthorized"
}

I've checked and triple-checked my client_id, client_secret, authorized hosts and redirect_uri, and looked through similar problems on stack overflow, but nothing seems to work... why is this happening to me :(

1

1 Answers

0
votes

It's because Google's guide/documentation are lying to you. That's not the right endpoint, and instead of saying so, it's giving you that extremely unhelpful error message. Hopefully, they'll be made aware of this SO post/answer and fix it. To find out the actual URL to use to obtain an authorization token, you can click on the "Download JSON" button on your credentials' view page on console.developers.google.com, instead of just copy/pasting the client_id and client_secret. Then you'll get something that looks like this:

{
    "web": {
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "client_id": "REDACTED",
        "client_secret": "REDACTED",
        "javascript_origins": [
            "https://localhost"
        ],
        "project_id": "REDACTED",
        "redirect_uris": [
            "https://localhost/sso?redirect=%2F"
        ],
        "token_uri": "https://oauth2.googleapis.com/token"
    }
}

and there you have it. The REAL token URI.