0

I'm trying to get a refreshed access token using the Youtube API v2 with C#. I'm doing it like this:

string _url = "client_id=" + HttpUtility.UrlEncode(_clientID) + "&client_secret=" + HttpUtility.UrlEncode(_clientSecret) + "&refresh_token=" + HttpUtility.UrlEncode(_refreshToken) + "&grant_type=refresh_token";

public string RefreshYoutubeToken(string _url) {
    string _response = "";
    TcpClient _tcpClient = new TcpClient("accounts.google.com", 443);
    Stream _netStream = _tcpClient.GetStream();
    SslStream _sslStream = new SslStream(_netStream);
    _sslStream.AuthenticateAsClient("accounts.google.com");
    {
        byte[] _contentAsBytes = Encoding.ASCII.GetBytes(_url.ToString());

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

        byte[] _headerAsBytes = Encoding.ASCII.GetBytes(_message.ToString());
        _sslStream.Write(_headerAsBytes);
        _sslStream.Write(_contentAsBytes);
    }

    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; }
        _response += _line;
        if(_line == "0") { break; }
    }
    return _response;
}

This works fine when I'm logging in and retrieving the access token for the first time, however, when I want to use the refresh token to retrieve a new access token, just like they describe at Google Developers - https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Refreshing_a_Token - I get an error returning invalid_grant.

I read somwhere that the problem may come from different Client - Server date times, and I concluded that in fact my Client date is about 3 seconds late than the Server, for example, Client 12:10:52 and Server 12:10:55.
I already tried changing the Client date time but with no luck.

Does anyone have any idea on how to solve this? Using this method or someother, I just need to refresh the access token.

4
  • Have a look at the underlying http post request and compare it to the oauth playground. The most likely cause is that your url or post data is wrong
    – pinoyyid
    Nov 20, 2013 at 15:21
  • @pinoyyid I've messed around and got to this result: POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-length: 211 Content-type: application/x-www-form-urlencoded Authorization: Bearer client_id=XXXXXXXXXXX& client_secret=XXXXXXXXXXX& refresh_token=XXXXXXXXXXX& grant_type=refresh_token however it returns invalid request. It's the same as this: goo.gl/FEIwj but it just does not work. Nov 20, 2013 at 16:51
  • when you xxxxxxx out the codes you are masking the problem. Just change a couple of random digits. I doubt anybody here is that interested in your Youtube videos. See my answer below
    – pinoyyid
    Nov 20, 2013 at 18:07
  • My request looks something like this: POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-length: 212 Content-type: application/x-www-form-urlencoded Authorization: Bearer client_secret=88HYtsb2pouLSWaFccaABoUS&grant_type=refresh_token&refresh_token=1%2fe_3odNbvh9gftc15Rn8KwCEc1ad4kgJfhsD_gno0wBw%7d0&client_id=508855465269-6hcrsfvlafn4k10256b78v8vgs459fgv.apps.googleusercontent.com Nov 20, 2013 at 18:44

2 Answers 2

0

Make sure you URL encode each of the form parameters rather than just appending them to _url - I think the following will help: http://msdn.microsoft.com/en-us/library/4fkewx0t(v=vs.110).aspx

Additionally make sure you are passing the refresh token (and not the access token or authorization code). It's not guaranteed to change, but currently it usually starts with "1/".

5
  • I already did that and if I encode the _url first the return error changes from invalid_grant to invalid_request. Given that I'm able to establish the first connection without enconding the url, I suppose I don't need to do it here, either way, neither works. Regarding the refresh_token, I'm using the correct one and it does start with "1/". Nov 20, 2013 at 17:11
  • I didn't mean to encode the entire _url, rather URL encode each of the parameters that make it up. That is: _url = "client_id=" + urlencode(client_id) + "&...". Can you confirm that is what you are already doing? (it wasn't clear either way in your comment) Nov 20, 2013 at 17:27
  • I was in fact encoding the whole _url, hence the invalid_request return. However, even if I encode every parameter, the return error is still invalid_grant. Nov 20, 2013 at 17:36
  • Your comment above to pinoyyid shows you are sending an "Authorization: Bearer ..." header - that isn't in your code above. Can you confirm you are not sending that now? (and maybe update your code in the question to reflect where you are now, URL encoding params etc - the rest looks good) Nov 20, 2013 at 17:45
  • The Authorization: Bearer ... comes from the OAuth Playground and I'm not sending it in my code. I've also read that if you use the ClientID to retrieve the access_token and want to use the refresh_token later on with the ClientID, it will not work. They said that you should use the EmailID instead, however that only applies to Web Apps, since in my case, Installed Apps, the EmailID does not exist. Nov 20, 2013 at 17:52
0

As @aeijdenberg, I suspect you aren't correctly urlencoding each parameter. Remember my advice is to go the Oauth Playground and see what it is sending. (The docs do NOT uri encode the params which is misleading)

So here is what your request should look like

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

client_secret=************&grant_type=refresh_token&refresh_token=1%2Fz5Ogwmp8TqDL31eU1L_Nhddiva_L_8tR7V9k&client_id=407408718192.apps.googleusercontent.com

If and only if, your request is exactly the same as this and you still get invalid grant, then there is a problem with your refresh token, so get a new one.

2
  • My request is exactly the same as yours and it does return invalid_grant in the OAuth playground. I already tried with a new refresh_token and the same thing happens. It is a fact that my access_token is still valid, but I already tried this, before and after the token expired and it always returns invalid_grant. In the API services I have the BigQuery, Freebase, YouTube Analytics and Youtube Data APIs ON, am I missing any service? Nov 20, 2013 at 18:27
  • I made a screenshot of the OAuthPlayground with my problem, can you tell me is there's something wrong here screenshot. Another thing I did, I removed the app permissions in the User Google account and gave them again with another authentication, but that didn't solve the problem. Nov 29, 2013 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.