How to Use Authentication by Xamarin.Auth in Xamarin.Forms



We always encounter the need for authentication in most of our applications. It's a struggling process to authenticate the user by interacting with services like Twitter, Facebook and so on.


Figure 1: Login

Here I'm creating a simple method of authentication using Xamarin.Auth.

The Xamarin.Auth component is a great time saver for authentication.

The authentication cardinals are given for authentication. Authenticators are responsible for managing the user interface and communicating with authentication services. Authenticators take a variety of parameters, like the Client ID, its authorization scope, the authorization URL, redirect URL and so on, since it varies depending on the authenticators.

  1. var auth = new OAuth2Authenticator  
  2. (  
  3. clientId: "", // your OAuth2 client id  
  4. scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols  
  5. authorizeUrl: new Uri(""), // the auth URL for the service  
  6. edirectUrl: new Uri("")  
  7. ); 
We want to listen to an authentication completed event that will be fired when the user is successfully authenticated or canceled.
  1. auth.Completed += (sender, args) =>   
  2. {  
  3. if(args.IsAuthenticated)  
  4. {  
  5. var account =args.Account;  
  6. // Do success work  
  7. }  
  8. else  
  9. {  
  10. // The user cancelled  
  11. {  
  12. };  
Authentication is the process of communication using the internet. Since there will be a time delay, as a result auth.Completed or auth.Error event handlers are asynchronously invoked after some significant delay.

All the info about the successful authentication will be in args.Account.

The GetUI() method returns the corresponding UINavigationController in iOS and corresponding Intent in Android.
  1. //iOS  
  2. PresentViewController (auth.GetUI (), true, null);  
  3. //Android  
  4. activity.StartActivity(auth.GetUI(activity));  
Xamarin.Auth always securely saves the login account data of the user , so it's not necessary for authentication of the user always.
  1. // On iOS:  
  2. AccountStore.Create ().Save (args.Account, "Facebook");  
  3.   
  4. // On Android:  
  5. AccountStore.Create (this).Save (args.Account, "Facebook");  
The AccountStore is responsible for all the user accounts stored. It's stored by Keychain in iOS and KeyStore in Android. The overwrite is also controlled.

Xamarin.Auth provides all the popular services for authentication. We can also create our own authenticator by Username and Password using FormAuthenticator.SignInAsync().

A small sample of Authentication sample is added with this article as a reference.

Up Next
    Ebook Download
    View all
    Learn
    View all