Youtube API C# OAuth token exchange for access_tok

2019-06-11 16:43发布

问题:

I'm trying to authenticate a user in his Google Account to access and modify his Youtube data. I managed to get the token returned from the user login and terms acceptance, but when I do the POST to exchange the token for a user access_token it returns an "invalid request" on the Json file.

Here's how I show the login page:

string url = string.Format("https://accounts.google.com/o/oauth2/auth?client_id=XXXXXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://gdata.youtube.com&response_type=code&access_type=offline");
WBrowser.Navigate(new Uri(url).AbsoluteUri);

I used a HttpWebRequest to make the POST

string url = "https://accounts.google.com/o/oauth2/token?code=XXXXXX&client_id=XXXXXXXXX&client_secret=XXXXXXXXX&redirect_uri=http://localhost/oauth2callback&grant_type=authorization_code";

HttpWebRequest httpWReq =  (HttpWebRequest)WebRequest.Create(url);

byte[] byteArray = Encoding.UTF8.GetBytes(url);

httpWReq.Method = "POST";
httpWReq.Host = "accounts.google.com";
httpWReq.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
httpWReq.ContentLength = byteArray.Length;

But it fails on this line:

HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpWReq.GetResponse();

With the following error:

You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.

I then changed my POST request to TcpClient like this:

TcpClient client = new TcpClient("accounts.google.com", 443);
Stream netStream = client.GetStream();
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient("accounts.google.com");
{
    byte[] contentAsBytes = Encoding.ASCII.GetBytes(url.ToString());

    StringBuilder msg = new StringBuilder();
    msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
    msg.AppendLine("Host: accounts.google.com");
    msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
    msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
    msg.AppendLine("");
    Debug.WriteLine("Request");
    Debug.WriteLine(msg.ToString());
    Debug.WriteLine(url.ToString());

    byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
    sslStream.Write(headerAsBytes);
    sslStream.Write(contentAsBytes);
}

Debug.WriteLine("Response");

StreamReader reader = new StreamReader(sslStream);
while(true) {  // Print the response line by line to the debug stream for inspection.
    string line = reader.ReadLine();
    if(line == null)
        break;
    Debug.WriteLine(line);
}

But returns the following in the JSon file:

{
  "error" : "invalid_request"
}

I'm follwoing the Youtube API: https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Installed_Applications_Flow

And you can test OAuth here: https://developers.google.com/oauthplayground/

Any suggestions on other ways to do this, or how to correct what I have?

回答1:

You're making a POST with ContentType = "application/x-www-form-urlencoded; charset=utf-8"; and a content length, but then passing the parameters in the URL.

A simple copy/paste from the oauth playground shows what your post should look like...

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-length: 250
content-type: application/x-www-form-urlencoded
user-agent: google-oauth-playground

code=4%2FfTu47TyLyXFg6eM2TcKv_ikQ1JJ1.kmu1bd6T8vsVXE-sT2ZLcbQH1fhchAI&redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&client_id=407408718192.apps.googleusercontent.com&scope=&client_secret=************&grant_type=authorization_code

Note the URL encoding!

Also, last time I tried, using localhost for a redirect URL wasn't allowed. Try mapping localhost to (say) devserver.mydomain.com in your etc/hosts file and specifying that as your redirect URL. Make sure you also add this in the API Console.



回答2:

Uri string and HTTP headers are not part of the content. So, just assign ContentLength to zero:

httpWReq.ContentLength = 0;


回答3:

I finally managed to solve this. I ended up using the TcpClient version, since it was the first I managed to get working. So the final code is something like this:

string _clientID = HttpUtility.UrlEncode("XXXXXXXXXXX.apps.googleusercontent.com");
string _clientSecret = HttpUtility.UrlEncode("XXXXXXXXXX");
string _redirectUri = "urn:ietf:wg:oauth:2.0:oob";
string _code = HttpUtility.UrlEncode(token);

string url = "code=" + _code + "&client_id=" + _clientID + "&client_secret=" + _clientSecret + "&redirect_uri=" + _redirectUri + "&grant_type=authorization_code";

TcpClient client = new TcpClient("accounts.google.com", 443);
Stream netStream = client.GetStream();
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient("accounts.google.com");
{
    byte[] contentAsBytes = Encoding.ASCII.GetBytes(url.ToString());
    StringBuilder msg = new StringBuilder();
    msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
    msg.AppendLine("Host: accounts.google.com");
    msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
    msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
    msg.AppendLine("");
    Debug.WriteLine("Request");
    Debug.WriteLine(msg.ToString());
    Debug.WriteLine(url.ToString());
    byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
    sslStream.Write(headerAsBytes);
    sslStream.Write(contentAsBytes);
}
Debug.WriteLine("Response");
StreamReader reader = new StreamReader(sslStream);
while(true) {  // Print the response line by line to the debug stream for inspection.
    string line = reader.ReadLine();
    if(line == null)
        break;
    Debug.WriteLine(line);
}

The problem was with the passing url, I was passing the https://accounts.google.com/o/oauth2/token? when I shouldn't have.