このエントリは、Windows 8 Store apps Advent Calendarの12/10エントリです。
Facebookなど有名どころが採用している認証システムにOAuth2.0があります。残念ながら最近いろいろ迷走しているTwitter (もう僕らのTwitterじゃなくなっちゃったのね) はいろいろ小うるさいことを言っている割にはOAuth2.0化せずにOAuth1.xのままなので対応できませんが、OAuth2.0ならこれからのアプリ開発は非常に楽になります。
それが「Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync」メソッドの存在です。
AuthenticateAsyncメソッドのヘルプファイルによればパラメタは
- options
- requestUri
- callbackUri
との事です。
試しにFacebookにログインしてみましょう。
Imports Windows.Security.Authentication.Web
Public Class AuthModel
Implements INotifyPropertyChanged
Private Const OAuth2Url As String = "https://www.facebook.com/dialog/oauth" &
"?client_id={0}" &
"&display=popup" &
"&response_type=token" &
"&scope={1}" &
"&redirect_uri={2}" &
"×tamp={3}"
Private Const Scope As String = "user_photos,read_stream,publish_stream"
Public ReadOnly Property AuthUrl As String
Get
Return String.Format(OAuth2Url,
Settings.ClientId,
Net.WebUtility.UrlEncode(Scope),
System.Net.WebUtility.UrlEncode(Settings.RedirectUrl),
DateTime.Now.ToString("yyyyMMddHHmmss"))
End Get
End Property
Public Async Function OAuthLogin() As Task
Dim loginUrl As String = AuthUrl
Dim result As WebAuthenticationResult =
Await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
New Uri(loginUrl),
New Uri(Settings.RedirectUrl))
If result.ResponseStatus = WebAuthenticationStatus.Success Then
Dim accessToken As String = result.ResponseData.ToString
Dim prefix As String = Me.CallbackPrefix
If accessToken.StartsWith(prefix) Then
accessToken = accessToken.Substring(prefix.Length)
If accessToken.IndexOf("&") >= 0 Then
accessToken = accessToken.Substring(0, accessToken.IndexOf("&"))
End If
Settings.AccessToken = accessToken
End If
End If
End Function
Public ReadOnly Property CallbackPrefix As String
Get
Return Settings.RedirectUrl & "#access_token="
End Get
End Property
Public Event PropertyChanged(sender As Object,
e As PropertyChangedEventArgs) _
Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal propertyName As String)
RaiseEvent PropertyChanged(Me,
New PropertyChangedEventArgs(propertyName))
End Sub
End Class
AuthenticateAsyncメソッドの特徴はUIを作らなくてもよいという点です。上記コードのOAuthLoginをコースすればFacebookの「サービスに接続してます」画面が表示され、Facebookにログインできます。