C# WPF初心者のCoreTweet入門2 認証
これはC# WPF初心者のCoreTweet入門1 - 01647に続く記事.主として編集するソースコードファイルMainWindow.xamlとMainWindow.xaml.csはまだ初期状態(https://gist.github.com/ustreamer-01647/a3c52b6305b2ca938c36/cb85df4cd79440fae4bc2b1dfb06a2f2689eb8dc).
GUI
ボタンを2個,ラベルを2個とテキストボックスを3個置く.認証手順は
- startSettingをクリック
- アクセス先を表示する
- Access here: のアドレスをブラウザにコピペしてもらってPINを得てもらう
- PIN入力してcertificateボタンをクリック
- pinResultTextboxに結果を表示する
<Window x:Class="testCoreTweet.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="470.455" Width="664.773"> <Grid> <Button x:Name="startSettingButton" Content="startSetting" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="99"/> <Label Content="Access here:" HorizontalAlignment="Left" Margin="114,10,0,0" VerticalAlignment="Top" Width="88"/> <TextBox x:Name="pinUritextbox" HorizontalAlignment="Left" Height="23" Margin="207,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="440"/> <TextBox x:Name="pinTextbox" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Margin="67,48,0,0"/> <Label Content="PIN:" HorizontalAlignment="Left" Margin="10,48,0,0" VerticalAlignment="Top" Width="52"/> <Button x:Name="pinButton" Content="certificate" HorizontalAlignment="Left" Margin="207,47,0,0" VerticalAlignment="Top" Width="89"/> <TextBox x:Name="pinResultTextbox" HorizontalAlignment="Left" Height="23" Margin="329,48,0,0" TextWrapping="Wrap" Text="pinResultTextbox" VerticalAlignment="Top" Width="318"/> </Grid> </Window>
コーディング
startSettingをダブルクリック
startSettingクリック時処理を記述するが,その前に一作業する.
- using CoreTweet; を記述
- public partial class MainWindow : Windowにメンバ変数を作る
- CoreTweet.Tokens
- CoreTweet.OAuth.OAuthSession
- Twitter Application Managementで作っていたAPIキー.プログラム途中で書き換えないからconst修飾する
さて.NET Twitter ライブラリ「CoreTweet」 - Qiita 例0: 認証を基に書く.
private void startSettingButton_Click(object sender, RoutedEventArgs e) { session = OAuth.Authorize(ApiKey, ApiSecret); pinUritextbox.Text = session.AuthorizeUri.ToString(); }
実行してみる.startSettingをクリックして数秒後,Access here:にアドレスが表示される.しかしワードラップにより折り返されている.デザイナでテキストボックスをクリックした後,プロパティペインでwrapと入力し,設定項目を探す.TextWrappingをNoWrapに変更し,再度実行してみる.折り返しが無効になっている.
さて表示したアドレスにアクセスしよう.ツイッタースパムでも必ず経由する確認画面が現れる.承認すると数字7桁のPINが表示される.
certificateをダブルクリック
PIN入力を受け付け,ツイッターアカウントを使用可能にする処理を記述する.pinResultTextboxのテキストラップを無効化しておく.
private void pinButton_Click(object sender, RoutedEventArgs e) { tokens = session.GetTokens(pinTextbox.Text); pinResultTextbox.Text = tokens.ToString(); }
tokens.ToString()には情報が4種仕込まれていた.
- oauth_token
- oauth_token_secret
- oauth_consumer_key
- oauth_consumer_secret
無事に認証されたようだ.現時点のコードは https://gist.github.com/ustreamer-01647/a3c52b6305b2ca938c36/11dd2d13a3c726091965ff66833eb4a24c6d3878
後記
今回はTokens.ToString()したが,認証の無事を何で判定したら良いのか.次回はトークンのファイル入出力.