Search code examples
c#google-oauth

Google Auth Exchange Code For Token C#


guys When I make this http request, I am getting an error

The remote server returned an error: (400) Bad Request

        try
        {

            var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");

            string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", authCode, clientid, secret, redirectURI);
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            MessageBox.Show(responseString);



        }

        catch (WebException ex)
        {
            MessageBox.Show(ex.Message);
            return null;
        }
    }

I tried alot of stuff like: Other link requests, UrlEncode, to put the response in using(), but still this bad request. The point is to get the accces token from the response


Solution

  • My redirect URI was null, needed to be "urn:ietf:wg:oauth:2.0:oob". Tip: Don't become on 2HP. Rest