如何在UWP上实现Twitter的oauth2?

时间:2016-10-10 13:10:12

标签: c# twitter oauth uwp

我想在UWP上开发一个小型的Twitter应用程序。

  • GET oauth / authenticate
  • GET oauth / authorize
  • POST oauth / access_token
  • POST oauth / request_token
  • POST oauth2 / invalidate_token
  • POST oauth2 / token

这是更多信息。我糊涂了。所以我想通过ComsumerKey,ComsumerKeySecret,Callback Uri登录Twitter。并获取access_token以访问来自api.twitter.com的数据。 我认为我之前要使用POST oauth2 / token(是不是?)。

 <!-- begin snippet: C# hide: false console: true babel: false -->

 <!-- language: lang-html -->

 public async Task<string> GetAccessTokenBYAuthorizeTwitter()
        {
            //throw new NotImplementedException();
            var client = new HttpClient();
            string postData = "grant_type=client_credentials";
            var request = await client.PostAsync(ResourceUrl,new StringContent(postData));
            //request headers
            client.DefaultRequestHeaders.Add("Authorization", string.Format("Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(ComsumerKeyAndSecret))));
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            return await request.Content.ReadAsStringAsync();
        }

<!-- end snippet -->

示例:我尝试通过Vimeo登录并成功。

public async Task<string> AuthorizeWithVimeo()
    {
        var clientId = "b8e1bff5d5d1f2c90f61017b135960adb42f5fe2";

        var SpotifyUrl = "https://api.vimeo.com/oauth/authorize?client_id=" + Uri.EscapeDataString(clientId) + "&response_type=code&redirect_uri=" + Uri.EscapeDataString("https://example/callback") + "&state=xyzbc";
        var StartUri = new Uri(SpotifyUrl);
        var EndUri = new Uri("https://example/callback");

        WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
        if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
        {
            var responseData = WebAuthenticationResult.ResponseData;

            //await GetSpotifyUserNameAsync(WebAuthenticationResult.ResponseData.ToString());
            return responseData;
        }
        else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
        {
            return $"HTTP Error returned by AuthenticateAsync() : {WebAuthenticationResult.ResponseErrorDetail.ToString()}";
        }
        else
        {
            return $"Error returned by AuthenticateAsync() : {WebAuthenticationResult.ResponseStatus.ToString()}";
        }
    }

1 个答案:

答案 0 :(得分:0)

这应该有效

var client = new HttpClient();

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Basic",
    Convert.ToBase64String(
        Encoding.ASCII.GetBytes(
            string.Format("{0}:{1}", Uri.EscapeDataString(oauth_consumer_key),
                          Uri.EscapeDataString(oauth_consumer_secret)))));

client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip");
client.DefaultRequestHeaders.TryAddWithoutValidation("Host", "api.twitter.com");

var content = new StringContent(postBody);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response =await client.PostAsync(oauth_url, content);
response.EnsureSuccessStatusCode();

using (var responseStream = response.Content.ReadAsStreamAsync())
using (var decompressedStream = new GZipStream(responseStream.Result, CompressionMode.Decompress))
using (var streamReader = new StreamReader(decompressedStream))
{
var rawJWt = streamReader.ReadToEnd();
var jwt = JsonConvert.DeserializeObject(rawJWt);
}

More info