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?