I am trying to get an access_token from Google in a Titanium application to access the Google+ API. I have registered an Android Oauth2.0 client in the Google API Console so i have a Client ID and a couple of redirect uris generated by Google: ["urn:ietf:wg:oauth:2.0:oob","http://localhost"]. I am trying to follow the authorization code flow, so i have made an authorization request to the endpoint "https://accounts.google.com/o/oauth2/v2/auth" with the following parameters as query strings:
client_id = encodeURI(<app id>)
redirect_uri = encodeURI("urn:ietf:wg:oauth:2.0:oob")
response_type = "code",
state = <random generated number>
scope = "https://www.googleapis.com/auth/plus.me"
Then i create a webview and redirect to the authorization endpoint with the appendend query strings. The google login screen opens and i can login and grant access to the application. In return i get an url with the authorization code embedded which i can extract to use for the next call.
To get the access_token i make a POST request to "https://accounts.google.com/o/oauth2/v2/auth" endpoint. This is the function:
function getAccessToken(code) {
Ti.API.warn("Authorization code: " + code);
var auth_data = {
code : code,
client_id : client_id,
redirect_uri : redirect_uri,
grant_type : "authorization_code",
};
var client = Ti.Network.createHTTPClient({
onload: function() {
var response_data = JSON.parse(this.responseText);
var access_token = response_data["access_token"];
var expires_in = response_data["expires_in"];
},
onerror: function() {
Ti.API.error("HTTPClient: an error occurred.");
Ti.API.error(this.responseText);
}
});
var body = "";
for (var key in auth_data) {
if (body.length) {
body += "&";
}
body += key + "=";
body += encodeURIComponent(auth_data[key]);
}
client.open("POST", "https://accounts.google.com/o/oauth2/v2/auth");
client.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
client.send(body);
}
But i got a status code of 400 with the following message: "Required parameter is missing: response_type".
I am not sure why i am getting this, since from OAuth 2.0 specification the required parameters for the access token request are just grant_type, code, client_id and redirect_uri. I have also tried to add response_type = "token" but that should be for the implicit flow if i understand correctly.
Any advice?
It seems i found the problem, the endpoint for the token exchange is not correct. It should be "https://accounts.google.com/o/oauth2/token", at least this one worked for me.
I would point out that in the latest documentation of Google the endpoint for the token exchange is this one: "https://accounts.google.com/o/oauth2/v2/token" but for some reason it doesn't work for me (the response says that the url is not supported by the server). Hope this can help people with similar issue.