LINQ to Twitter を利用してWindows FormアプリケーションでTwitter認証する - C#

LINQ to Twitter を利用してWindows FormアプリケーションでTwitter認証するコードを紹介します。
注意
この記事で紹介している方法は 2015年時点の方法です。Twitterの仕様変更等でこのコードでは動作しない可能性が高いため、ご注意ください。

プロジェクトへのLINQ to Twitterのインストール

こちらの記事を参照してnuGetを利用して、プロジェクトにLINQ to Twitterをインストールします。

プログラム

UI

下図のUIを作成します。Buttonを2つ、TextBoxを2つ配置します。テキストボックスの一つは複数行テキストボックスにします。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using LinqToTwitter;

namespace TwitterAuthWindowsForm
{
  public partial class FormMain : Form
  {
    private PinAuthorizer pa;

    public FormMain()
    {
      InitializeComponent();
      pa = new PinAuthorizer();
    }

    async private void button1_Click(object sender, EventArgs e)
    {
      pa.CredentialStore = new InMemoryCredentialStore();
      pa.CredentialStore.ConsumerKey = "(コンシューマーキー)";
      pa.CredentialStore.ConsumerSecret = "(コンシューマーシークレット)";

      pa.GoToTwitterAuthorization = pageLink => Process.Start(pageLink);

      await pa.BeginAuthorizeAsync();
    }

    async private void button2_Click(object sender, EventArgs e)
    {
      await pa.CompleteAuthorizeAsync(textBox1.Text);

      textBox2.Text += string.Format("OAuthToken:{0}\r\n", pa.CredentialStore.OAuthToken);
      textBox2.Text += string.Format("OAuthTokenSecret:{0}\r\n", pa.CredentialStore.OAuthTokenSecret);
      textBox2.Text += string.Format("ScreenName:{0}\r\n", pa.CredentialStore.ScreenName);
      textBox2.Text += string.Format("UserID:{0:d}\r\n", pa.CredentialStore.UserID);
    }
  }
}

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。ウィンドウの[button1]をクリックします。


Webブラウザが開き、Twitterの認証画面のページが表示されます。認証するユーザー名とパスワードを入力し、[連携アプリを認証]ボタンをクリックします。


7桁のPINコードが表示されます。


PINコードを元のアプリケーションのテキストボックスに入力し、[button2]をクリックします。


トークンの取得処理が実行され、下部のテキストボックスに、OAuthのトークンが表示されます。


以上でWindows FormでのTwitterのOAuth認証ができました。

著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-07
作成日: 2015-04-06
iPentec all rights reserverd.