使用HttpClient获取承载令牌

时间:2015-10-03 13:47:15

标签: c# oauth dotnet-httpclient

我正在尝试获取持有人令牌:

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);
}

这给了我以下错误403&#39; Forbidden&#39;。任何想法,将不胜感激。

1 个答案:

答案 0 :(得分:11)

我能够让这个工作。我在上面的代码中改变了一些东西。首先是设置ContentType

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

其次是我错过的一个非常小的细节,降低了Basic标题中Authorization字符串的大小写。

以下是完整的方法以防万一有人需要它:

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();

}