古事連記帖

趣味のこと、技術的なこと、適当につらつら書きます。

CoreTweet を使って WebAuthenticationBroker で Twitter 認証する

なんとなくメモ

id:kaorun さんが同じように Twitter 認証する方法を記事にしていますが、2014 年と古いのと、Windows 8.1 時代のネタなので UWP 向けに書き換えてみます*1
d.hatena.ne.jp


UWP になってから、Mobile 版でも AndContinue なメソッドを使って気合いでやるようなことをしなくてもよくなりました。それを踏まえてこんな感じで書いてみました。

using System;
using CoreTweet;
using Windows.Foundation;
using Windows.Security.Authentication.Web;

public class TwitterAuthenticator
{
    const string ConsumerKey = "";
    const string ConsumerSecret = "";

    public async Task<Tokens> AuthenticationAsync()
    {
        var redirectUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
        var session = await OAuth.AuthorizeAsync(ConsumerKey, ConsumerSecret, redirectUrl.ToString());

        var broker = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, 
            session.AuthorizeUri, redirectUrl);

        if (broker.ResponseStatus == WebAuthenticationStatus.Success)
        {
            var responseUri = new Uri(broker.ResponseData);
            var decoder = new WwwFormUrlDecoder(responseUri.Query);
            var tokens = await session.GetTokensAsync(decoder.GetFirstValueByName("oauth_verifier"));

            return tokens;
        }
        else
        {
            // エラーとか
        }

        return null;
    }
}

だいぶすっきりしました。CoreTweet のチカラ全開っすね
github.com

*1:と言っても、同じ WinRT なのであんまし変わらないですけどね