0

I'm trying to exchange the authorization code I got in this step of the documentation for refresh and access tokens. Where I'm stuck is how to send a request for the Json that contains the access and refresh tokens as described here.

This is my code:

string paras = string.Format("code={0}&client_id={1}&client_secret={2}&grant_type={4}&redirect_uri={3}",
    AuthCode,
    ClientID,
    ClientSecret,
    "urn:ietf:wg:oauth:2.0:oob",
    "authorization_code"
);
var req = WebRequest.Create("https://www.googleapis.com/oauth2/v4/token/") as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] data = Encoding.UTF8.GetBytes(paras);
req.ContentLength = data.Length;
using (Stream stream = req.GetRequestStream())
    stream.Write(data, 0, data.Length);
req.GetResponse();

System.Net.WebException: 'The remote server returned an error: (400) Bad Request.' is being thrown at req.GetResponse();.

My two theories are either I need to add a redirect uri in the developer console and use that or add a code verifier.

TrueCP5
  • 358
  • 3
  • 14

2 Answers2

2

The redirect_uri must be the same as when the authorization code was requested.

I also missed this step. The code_challenge can be the same as code_verifier but only if code_challenge_method is plain. The documentation says that it is only "recommended" for requesting the authorization code when it is in fact required for later.

TrueCP5
  • 358
  • 3
  • 14
1

When issuing a request to https://accounts.google.com/o/oauth2/v2/auth to initiate the OAuth2 flow and obtain an Auth Code (OAuth 2.0 Step 2), the redirect_uri parameter accepts the special urn:ietf:wg:oauth:2.0:oob URI to specify manual copy/paste of the obtained response.

However, in the OAuth 2.0 Step 5 (exchanging auth code for refresh & access token) the redirect_uri parameter does not accept the aforementioned URI, so you will have to use a valid one that has been set up in your GCP project (you can add one by going to credentials>your credential>Authorized redirect URIs).

Furthermore, in order to debug response errors returned by the API, I suggest you check out this link that describes how to obtain and print the information that is returned along with a failed request.

carlesgg97
  • 4,184
  • 1
  • 8
  • 24