0
votes

I'm trying to get access_token from google (youtube), I followed the documentation, but the response is 400 - bad request.

            NameValueCollection parameters = new NameValueCollection();
            parameters.Add("client_id", _clientID);
            parameters.Add("client_secret", _clientSecret);
            parameters.Add("grant_type", "authorization_code");
            parameters.Add("redirect_uri", redirectUri);
            parameters.Add("code", Url.Encode(code));
            parameters.Add("content-type", "application/x-www-form-urlencoded");

            WebClient client = new WebClient();
            var result = client.UploadValues("https://accounts.google.com/o/oauth2/token", "POST", parameters);

In the docs I've found the url: https://oauth2.googleapis.com/token Response: System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'

I've tried: https://www.googleapis.com/oauth2/v4/token Response: System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'

And: https://accounts.google.com/o/oauth2/token Response: System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'

Could you please help to solve this ?

Thanks in advance

1

1 Answers

0
votes

I had to write the header part into the WebClient and no need to encode the 'code'

            NameValueCollection parameters = new NameValueCollection();
            parameters.Add("client_id", _clientID);
            parameters.Add("client_secret", _clientSecret);
            parameters.Add("grant_type", "authorization_code");
            parameters.Add("redirect_uri", redirectUri);
            parameters.Add("code", code);

            WebClient client = new WebClient();
            client.Headers.Add("content-type", "application/x-www-form-urlencoded");
            var result = client.UploadValues("https://oauth2.googleapis.com/token", "POST", parameters);

Works well like this.