Making a POST request to Google OAuth using WWWForms
Hi, I'm trying to write a WWWForm to make a HTTP POST request to exchange an auth code for an access token. This is my first time working with WWWForms and I would like a bit of guidance.
Google gives an example of the request:
 POST /oauth2/v4/token HTTP/1.1
 Host: www.googleapis.com
 Content-Type: application/x-www-form-urlencoded
 
 code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
 client_id=8819981768.apps.googleusercontent.com&
 client_secret=your_client_secret&
 redirect_uri=https://oauth2.example.com/code&
 grant_type=authorization_code
 
               I retrieve my auth code using GetServerAuthCode(), and pass that to this function:
         public IEnumerator GetGoogleAccessToken(string auth_code) {
             WWWForm form = new WWWForm();
     
             Dictionary<string, string> headers = new Dictionary<string, string>();
    
             headers.Add("Host", "www.googleapis.com");
             headers.Add("Content-Type", "application/x-www-form-urlencoded");
             form.AddField("code", auth_code + "&");
             form.AddField("client_id", client_id);
             form.AddField("client_secret", client_secret);
             form.AddField ("redirect_uri", redirect_uri);
             form.AddField("grant_type", "authorization_code");
             byte[] rawData = form.data;
 
             WWW www = new WWW(token_uri, rawData, headers);
             yield return www;
         }
 
               Am I suppose to append '&' to the end of all my strings?
Referring to this, section 4: https://developers.google.com/identity/protocols/OpenIDConnect I believe that my endpoint url should be
https://www.googleapis.com/oauth2/v4/token? Does that seem correct?Why is it that when I do not modify headers, I can call
WWW(url, form), but when I do, I have to callWWW(url, rawData, headers)? In other words, how does sending a form differ from sending a byte array?I'm expecting JSON data to be return. Any examples or suggestions on how I should parse that in C#?
Thank you!
Answer by RudyDev · Sep 12, 2016 at 01:09 AM
I managed to get a response, albeit an error:
 {
    "error": "invalid_client",
    "error_description": "The OAuth client was not found."
 }
 
               I'm using a Web Application Client ID generated from the Google Developer Console.
Is it possible that I need to encode my URL in some way? I'm simply passing it as a string via client_id
Googled this issue, people report changing the Product name to equal the Project name (In Credentials) will solve this. I have them both the same, but the issue persists.
An feedback would help, thanks!
Your answer
 
             Follow this Question
Related Questions
Unable to authenticate using Firebase Auth 0 Answers
Unity Google Play Services 2 Answers
Game Native SDK error 0 Answers
user can't log into google play services 1 Answer
The best overloaded method match for google play games 1 Answer