lathomas64
lathomas64

Reputation: 1642

twitter application oauth 403

I am attempting to do application oauth as outlined here: https://dev.twitter.com/docs/api/1.1/post/oauth2/token

but my attempts to do so result in 403(forbidden) The C# code I am attempting is:

String key = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            String secret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];

            String bearerCredentials = HttpUtility.UrlEncode(key) + ":" + HttpUtility.UrlEncode(secret);
            bearerCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(bearerCredentials));

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/oauth2/token");            
            request.Method = "POST";
            request.Headers.Add("Authorization", "Basic " + bearerCredentials);
            request.ContentType = "Content-Type: application/x-www-form-urlencoded;charset=UTF-8";
            string postData = "grant_type=client_credentials";
            byte[] data = System.Text.Encoding.UTF8.GetBytes(postData);            
            request.ContentLength = data.Length;
            request.GetRequestStream().Write(data, 0, data.Length);   
            WebResponse response = request.GetResponse();

Any suggestions on what I am doing wrong here?

Upvotes: 1

Views: 1439

Answers (1)

lathomas64
lathomas64

Reputation: 1642

Leaving this question up in case someone else makes the same silly mistake I did, writing it up pointed out to me the answer this line

request.ContentType = "Content-Type: application/x-www-form-urlencoded;charset=UTF-8";
            string postData = "grant_type=client_credentials";

had an unecessary Content-Type being set it should be

request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            string postData = "grant_type=client_credentials";

Upvotes: 3

Related Questions