Twitter の次は Facebook ということで、Xamarin.Forms で OAuth 認証をやってみます
まずはアプリケーションの登録、下記のページを開きます
http://developers.facebook.com/setup/
必要事項を入力すると・・・
このセキュリティチェックは評価する!!
登録されたアプリページの左メニューから「Setting」を開くと、App ID や App Secret が表示されるのでメモしておきます
さらに真ん中のタブ「Advanced」を開くと中ほどに「Client OAuth Settings」というフォームがあります
「Embedded Browser OAuth Login」「Web OAuth Login」など必要に応じてを「Yes」にしておきます
さらに「Valid OAuth redirect URIs」の項目、ここに「http://www.facebook.com/connect/login_success.html」を入力します
※これは WebView で OAuth 認証した場合の結果を受け取るために必要です
最後に「Login from Devices」も「Yes」
とりあえず設定終わり!Xamarin.Forms で次のようなコードを書きました
/// <summary> /// App ID /// </summary> private const string AppId = @"App ID"; /// <summary> /// Secret Key /// </summary> private const string AppSecret = @"App Secret"; /// <summary> /// Page appearing event handler /// </summary> protected override void OnAppearing() { base.OnAppearing(); // Navigate to facebook authorize page this.webView.Source = string.Format(@"https://m.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}&response_type=token", AppId, WebUtility.UrlEncode(@"http://www.facebook.com/connect/login_success.html")); this.webView.Navigating += this.OnNavigating; } /// <summary> /// WebView navigating event handler /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event arguments</param> private void OnNavigating(object sender, WebNavigatingEventArgs e) { if (e.Url.StartsWith(@"http://www.facebook.com/connect/login_success.html")) { this.webView.Navigating -= this.OnNavigating; var uri = new Uri(e.Url); if (!string.IsNullOrEmpty(uri.Fragment) && uri.Fragment.StartsWith("#access_token")) { // Login succeeded var token = uri.Fragment.Split('&').First().Split('=').LastOrDefault(); DisplayAlert("XamarinFacebook", string.Format("OAuth 認証に成功しました, token={0}", token), "OK"); } else { // Login failed DisplayAlert("XamarinFacebook", "OAuth 認証に失敗しました", "OK"); } } }
WebView で https://m.facebook.com/dialog/oauth を開いて、http://www.facebook.com/connect/login_success.html に戻ってきたらパラメータから結果を判定しています
実行してみた様子はこんな感じ・・・Facebook はライブラリがなくてもかんたんですね