Search code examples
c#.netoauth-2.0google-drive-apihttpwebrequest

Exchanging authorization code for refresh and access tokens OAuth2


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.


Solution

  • 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.