Search code examples
c#winformsoauth-2.0youtube-apigoogle-oauth

Trying to bring access token using approval code, client id, etc


I'm using C# to implement youtube login in my application and I was wondering why it is keep returning 'bad request' message whenever I request for access token I've got client id, client secret, redirect uri, etc to access but it keeps returning me bad request. Please tell me whats wrong with my code

            try
            {
                string clientId = "~~~";
                string clientSecret = "~~~";
                string redirectUri = "urn:ietf:wg:oauth:2.0:oob";
                string tokenEndpoint = "https://oauth2.googleapis.com/token";

                HttpClient client = new HttpClient();
                var content = new FormUrlEncodedContent(new[]
                {
            new KeyValuePair<string, string>("grant_type", "authorization_code"),
            new KeyValuePair<string, string>("code", code),
            new KeyValuePair<string, string>("redirect_uri", redirectUri),
            new KeyValuePair<string, string>("response_type", "token"),
            new KeyValuePair<string, string>("scope", "https://www.googleapis.com/auth/youtube"),
            new KeyValuePair<string, string>("client_id", clientId),
            new KeyValuePair<string, string>("client_secret", clientSecret)
        });


                HttpResponseMessage response = await client.PostAsync(tokenEndpoint, content);


Solution

  • First issue you can not use urn:ietf:wg:oauth:2.0:oob as a redirect uri you need to use localhost

    second the post body should be in the form of a query string

    code=[REDACTED]&client_id=[REDACTED]&client_secret=[REDACTED]&redirect_uri=https:\\127.0.0.1&grant_type=authorization_code
    

    third why not use the google .net client library?