public void StartAuthentication(string clientId, string scope, string appSecret, Uri authorizeUrl, Uri redirectUrl, Uri tokenUrl, bool codeChallengeMethod) { Xamarin.Auth.OAuth2Authenticator oAuth2 = new Xamarin.Auth.OAuth2Authenticator(clientId, appSecret, scope, authorizeUrl, redirectUrl, tokenUrl); oAuth2.Completed += OnOAuth2Completed; oAuth2.Error += OnOAuth2Error; Android.Content.Context context = Android.App.Application.Context; Android.Content.Intent loginUI = oAuth2.GetUI(context); loginUI.AddFlags(Android.Content.ActivityFlags.NewTask); context.StartActivity(loginUI); }
// IOAuthAuthorizeHandler.AuthorizeAsync implementation public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri) { // If the TaskCompletionSource is not null, authorization may already be in progress and should be cancelled if (_taskCompletionSource != null) { // Try to cancel any existing authentication task _taskCompletionSource.TrySetCanceled(); } // Create a task completion source _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >(); #if __ANDROID__ || __IOS__ #if __ANDROID__ // Get the current Android Activity Activity activity = (Activity)Android.App.Application.Context; #endif #if __IOS__ // Get the current iOS ViewController var viewController = Xamarin.Forms.Platform.iOS.Platform.GetRenderer(this).ViewController; #endif // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in Xamarin.Auth.OAuth2Authenticator authenticator = new Xamarin.Auth.OAuth2Authenticator( clientId: AppClientId, scope: "", authorizeUrl: authorizeUri, redirectUrl: callbackUri) { ShowErrors = false }; // Allow the user to cancel the OAuth attempt authenticator.AllowCancel = true; // Define a handler for the OAuth2Authenticator.Completed event authenticator.Completed += (sender, authArgs) => { try { #if __IOS__ // Dismiss the OAuth UI when complete viewController.DismissViewController(true, null); #endif // 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); } else { throw new Exception("Unable to authenticate user."); } } catch (Exception ex) { // If authentication failed, set the exception on the TaskCompletionSource _taskCompletionSource.TrySetException(ex); // Cancel authentication authenticator.OnCancelled(); } #if __ANDROID__ finally { // Dismiss the OAuth login activity.FinishActivity(99); } #endif }; // 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.TrySetException(errArgs.Exception); } else { // Login canceled: dismiss the OAuth login if (_taskCompletionSource != null) { _taskCompletionSource.TrySetCanceled(); #if __ANDROID__ activity.FinishActivity(99); #endif } } // Cancel authentication authenticator.OnCancelled(); }; // Present the OAuth UI so the user can enter user name and password #if __ANDROID__ var intent = authenticator.GetUI(activity); activity.StartActivityForResult(intent, 99); #endif #if __IOS__ // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password Device.BeginInvokeOnMainThread(() => { viewController.PresentViewController(authenticator.GetUI(), true, null); }); #endif #endif // Return completion source task so the caller can await completion return(_taskCompletionSource.Task); }
// IOAuthAuthorizeHandler.AuthorizeAsync implementation. 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> >(); // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in. _auth = new OAuth2Authenticator( clientId: AppClientId, scope: "", authorizeUrl: authorizeUri, redirectUrl: new Uri(OAuthRedirectUrl)) { // Allow the user to cancel the OAuth attempt. AllowCancel = true }; // Define a handler for the OAuth2Authenticator.Completed event. _auth.Completed += (object sender, AuthenticatorCompletedEventArgs args) => { try { // Dismiss the OAuth UI when complete. this.DismissViewController(true, null); // Throw an exception if the user could not be authenticated. if (!args.IsAuthenticated) { throw new Exception("Unable to authenticate user."); } // If authorization was successful, get the user's account. Xamarin.Auth.Account authenticatedAccount = args.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); } }; // If an error was encountered when authenticating, set the exception on the TaskCompletionSource. _auth.Error += (object sender, AuthenticatorErrorEventArgs args) => { if (args.Exception != null) { _taskCompletionSource.TrySetException(args.Exception); } else { _taskCompletionSource.TrySetException(new Exception(args.Message)); } }; // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password. InvokeOnMainThread(() => { this.PresentViewController(_auth.GetUI(), true, null); }); // Return completion source task so the caller can await completion. return(_taskCompletionSource.Task); }
// IOAuthAuthorizeHandler.AuthorizeAsync implementation. public Task <IDictionary <string, string> > AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri) { // If the TaskCompletionSource is not null, authorization may already be in progress and should be canceled. // Try to cancel any existing authentication process. _taskCompletionSource?.TrySetCanceled(); // Create a task completion source. _taskCompletionSource = new TaskCompletionSource <IDictionary <string, string> >(); // Create a new Xamarin.Auth.OAuth2Authenticator using the information passed in. _auth = new OAuth2Authenticator( clientId: AppClientId, scope: "", authorizeUrl: authorizeUri, redirectUrl: new Uri(OAuthRedirectUrl)) { ShowErrors = false, // Allow the user to cancel the OAuth attempt. AllowCancel = true }; // Define a handler for the OAuth2Authenticator.Completed event. _auth.Completed += (o, authArgs) => { try { // Dismiss the OAuth UI when complete. InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null); }); // 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); } else { throw new Exception("Unable to authenticate user."); } } catch (Exception ex) { // If authentication failed, set the exception on the TaskCompletionSource. _taskCompletionSource.TrySetException(ex); // Cancel authentication. _auth.OnCancelled(); } }; // If an error was encountered when authenticating, set the exception on the TaskCompletionSource. _auth.Error += (o, errArgs) => { // If the user cancels, the Error event is raised but there is no exception ... best to check first. if (errArgs.Exception != null) { _taskCompletionSource.TrySetException(errArgs.Exception); } else { // Login canceled: dismiss the OAuth login. _taskCompletionSource?.TrySetCanceled(); } // Cancel authentication. _auth.OnCancelled(); _auth = null; }; // Present the OAuth UI (on the app's UI thread) so the user can enter user name and password. InvokeOnMainThread(() => { UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(_auth.GetUI(), true, null); }); // Return completion source task so the caller can await completion. return(_taskCompletionSource.Task); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); spinner = FindViewById <Spinner>(Resource.Id.spinner); var adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerItem, new string[] { "<none>", "Profile", "Activity", "Heart Rate", "Sleep" }); adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); spinner.Adapter = adapter; spinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { if (e.Id == 1) //get profile { GetData(Constants.Fitbit.ProfileUrl); } else if (e.Id == 2) //get activity { GetData(Constants.Fitbit.ActivityUrl.Replace("[date]", DateTime.Today.ToString("yyyy-MM-dd"))); } else if (e.Id == 3) // get heart rate { GetData(Constants.Fitbit.HeartRateUrl.Replace("[date]", "today").Replace("[range]", "1d")); } else if (e.Id == 4) //Sleep { GetData(Constants.Fitbit.SleepUrl.Replace("[date]", DateTime.Today.ToString("yyyy-MM-dd"))); } }; spinner.Enabled = false; textResult = FindViewById <EditText>(Resource.Id.editText1); Button button1 = FindViewById <Button>(Resource.Id.button1); // wire up add task button handler if (button1 != null) { button1.Click += (sender, e) => { Toast.MakeText(this, "Trying to authenticate with fitbit!", ToastLength.Short); //store = AccountStore.Create(this, "test123"); //account = store.FindAccountsForService(Constants.Fitbit.AppName).FirstOrDefault(); /*** OAuth2Authenticator object fails to authenticate with fitbit (it works for google though). However, it fires the OnAuthError method which we can use our way to get around the authentication. * we simply use it currently to present the fitbit authentication screen for the user, and make use of the OnAuthError event to proceed with our authentication mechanism. */ authenticator = new OAuth2Authenticator(Constants.Fitbit.AndroidClientId, Constants.Fitbit.ClientSecret, Constants.Fitbit.Scope, new Uri(Constants.Fitbit.AuthorizeUrl), new Uri(Constants.Fitbit.AndroidRedirectUrl), new Uri(Constants.Fitbit.AccessTokenUrl), null, true); authenticator.AllowCancel = true; authenticator.Completed += OnAuthCompleted; authenticator.Error += OnAuthError; AuthenticationState.Authenticator = authenticator; auth_ui = authenticator.GetUI(this); StartActivity(auth_ui); }; } }