【问题标题】:How to implement oauth2 of Twitter on UWP?如何在 UWP 上实现 Twitter 的 oauth2?
【发布时间】:2017-02-18 22:09:42
【问题描述】:

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

  • GET oauth/authenticate
  • 获取认证/授权
  • 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()}";
        }
    }

【问题讨论】:

  • 您访问的是什么 api?客户特定或公共数据有不同的用户数据流
  • 首先,我需要先登录并获取访问令牌...

标签: c# twitter oauth uwp


【解决方案1】:

这应该可以工作

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多