Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain Bearer Token using HttpClient

I am trying to obtain bearer token:

public override async Task<string> Post(string path, HttpContent content) {


    var encodedConsumerKey = System.Uri.EscapeDataString("1111111111111");
    var encodedConsumerKeySecret = System.Uri.EscapeDataString("2222222222222");
    var encodedPair = Base64Encode(String.Format("{0}:{1}", encodedConsumerKey, encodedConsumerKeySecret));

    HttpRequestMessage request = new HttpRequestMessage{
                                        Method      = HttpMethod.Post,
                                        RequestUri  = new Uri("https://api.twitter.com/oauth2/token"),
                                        Content     = new StringContent("grant_type=client_credentials")
                                    };
    request.Headers.TryAddWithoutValidation("Authorization", String.Format("BASIC {0}", encodedPair));
    request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");


    var result = await HttpClient.SendAsync(request);
    return result.Content.ReadAsStringAsync().Result;
}

private static string Base64Encode(string plainText) {
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    return System.Convert.ToBase64String(plainTextBytes);
}

This is giving me the following error 403 'Forbidden'. Any ideas would be appreciated.

like image 815
Jose Capistrano Avatar asked Oct 03 '15 13:10

Jose Capistrano


1 Answers

I was able to get this working. I changed a couple of things in the code above. First is setting the ContentType

requestToken.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded") {CharSet = "UTF-8"};

Second is one very small detail I missed, lowering the case of the Basic string in the Authorization header.

Here's the complete method just in case anyone would need it:

public async Task<string> GetAPI(string apiPath)
{

var baseUri = new Uri("https://api.twitter.com/");
var encodedConsumerKey = HttpUtility.UrlEncode("111111111111");
var encodedConsumerKeySecret = HttpUtility.UrlEncode("222222222222");
var encodedPair = Base64Encode(String.Format("{0}:{1}", encodedConsumerKey, encodedConsumerKeySecret));

var requestToken = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri(baseUri, "oauth2/token"),
    Content = new StringContent("grant_type=client_credentials")
};

requestToken.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded") { CharSet = "UTF-8" };
requestToken.Headers.TryAddWithoutValidation("Authorization", String.Format("Basic {0}", encodedPair));

var bearerResult = await HttpClient.SendAsync(requestToken);
var bearerData = await bearerResult.Content.ReadAsStringAsync();
var bearerToken = JObject.Parse(bearerData)["access_token"].ToString();

var requestData = new HttpRequestMessage
{
    Method = HttpMethod.Get,
    RequestUri = new Uri(baseUri, apiPath),
};
requestData.Headers.TryAddWithoutValidation("Authorization", String.Format("Bearer {0}", bearerToken));

var results = await HttpClient.SendAsync(requestData);
return await results.Content.ReadAsStringAsync();

}
like image 63
Jose Capistrano Avatar answered Nov 09 '22 00:11

Jose Capistrano