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.
- var auth = new OAuth2Authenticator
- (
- clientId: "", // your OAuth2 client id
- scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
- authorizeUrl: new Uri(""), // the auth URL for the service
- edirectUrl: new Uri("")
- );
We want to listen to an authentication completed event that will be fired when the user is successfully authenticated or canceled.
- auth.Completed += (sender, args) =>
- {
- if(args.IsAuthenticated)
- {
- var account =args.Account;
- // Do success work
- }
- else
- {
- // The user cancelled
- {
- };
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.
- //iOS
- PresentViewController (auth.GetUI (), true, null);
- //Android
- 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.
- // On iOS:
- AccountStore.Create ().Save (args.Account, "Facebook");
-
- // On Android:
- 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.