public Task<IDictionary<string, string>> AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri)
{
// If the TaskCompletionSource is not null, authorization is in progress
if (_taskCompletionSource != null)
{
// Allow only one authorization process at a time
throw new Exception();
}
// Create a task completion source
_taskCompletionSource = new TaskCompletionSource<IDictionary<string, string>>();
var activity = Context as Activity;
// Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in
var authenticator = new OAuth2Authenticator(
clientId: OAuthPage.AppClientId,
scope: "",
authorizeUrl: new Uri(OAuthPage.AuthorizeUrl),
redirectUrl: new Uri(OAuthPage.OAuthRedirectUrl));
// Allow the user to cancel the OAuth attempt
authenticator.AllowCancel = true;
// Define a handler for the OAuth2Authenticator.Completed event
authenticator.Completed += (sender, authArgs) =>
{
try
{
// Check if the user is authenticated
if (authArgs.IsAuthenticated)
{
// If authorization was successful, get the user's account
Xamarin.Auth.Account authenticatedAccount = authArgs.Account;
// Set the result (Credential) for the TaskCompletionSource
_taskCompletionSource.SetResult(authenticatedAccount.Properties);
}
}
catch (Exception ex)
{
// If authentication failed, set the exception on the TaskCompletionSource
_taskCompletionSource.SetException(ex);
}
finally
{
// End the OAuth login activity
activity.FinishActivity(99);
}
};
// If an error was encountered when authenticating, set the exception on the TaskCompletionSource
authenticator.Error += (sndr, errArgs) =>
{
// If the user cancels, the Error event is raised but there is no exception ... best to check first
if (errArgs.Exception != null)
{
_taskCompletionSource.SetException(errArgs.Exception);
}
else
{
// Login canceled: end the OAuth login activity
if (_taskCompletionSource != null)
{
_taskCompletionSource.TrySetCanceled();
activity.FinishActivity(99);
}
}
};
// Present the OAuth UI (Activity) so the user can enter user name and password
var intent = authenticator.GetUI(activity);
activity.StartActivityForResult(intent, 99);
return _taskCompletionSource.Task;
}
#endregion