javascripthtmlgoogle-apigoogle-oauth

Google OAuth2 giving "Invalid grant_type" error


I've been wrestling with learning how to interact with google's api, including learning to use OAuth2. I've gotten most of the way there - I've got the authorization code. Now I'm trying to trade that in for an access token but I keep getting a unsupported_grant_type error. I've triple checked and I made the grant_type authorization_code which I'm pretty sure is what it's supposed to be.

I haven't been able to find very many examples or answers of how to do this in html and javascript so I've come here for help.

Here's my code for getting the token:

function getToken(){
   let credentials;
   var data = {'code': authCode,
               'client_id': clientid
               'client_secret': clientsecret,
               'redirect_uri': redirecturi,
               'grant_type': 'authorization_code'};
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "https://oauth2.googleapis.com/token");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200){
          credentials = JSON.parse(this.response);
          gapi.client.SetToken(credentials.access_token);
       }
       else {
          document.getElementById("error").innerHTML = this.readyState + " + " + this.response;
                      
       }
    }
    xhr.send(data);
}

(authCode, clientid, clientsecret, and redirecturi are all either predefined variables or replaced for security)

This creates the output:

3 + { "error": "unsupported_grant_type", "error_description": "Invalid grant_type: " }

Can anyone give me a hint as to what I might be doing wrong?


Solution

  • most likely its the encoding of the body ,When using application/x-www-form-urlencoded, the data should be formatted as a URL-encoded string.

    try this

    function getToken() {
        let credentials;
        var data = `code=${encodeURIComponent(authCode)}` +
                   `&client_id=${encodeURIComponent(clientid)}` +
                   `&client_secret=${encodeURIComponent(clientsecret)}` +
                   `&redirect_uri=${encodeURIComponent(redirecturi)}` +
                   `&grant_type=authorization_code`;
    
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "https://oauth2.googleapis.com/token");
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                credentials = JSON.parse(this.response);
                gapi.client.setToken(credentials.access_token);
            } else {
                document.getElementById("error").innerHTML = this.readyState + " + " + this.response;
            }
        };
        xhr.send(data);
    }