Store User Credentials using Xamarin.Auth in Xamarin.Forms

If you are working on Mobile Apps, it won’t be long before you end up with a scenario to store User Account objects locally so that the user needn’t go through the pain of authenticating himself all over again, every time he logs in. One of the easiest way to do is via the cross platform Xamarin.Auth SDK  (Click here for Details).

The SDK uses Keychain Services for iOS and KeyStore Class for Android for its implementation.

Like always with any platform specific implementation, we would be using DepedencyService to define the platform specific behavior, in this case, the SDK uses KeyChain Services for iOS and KeyStore for Droid. Let’s go ahead and declare the Interface first.

public interface IAuthService
 {
 void SaveCredentials(string UserName, string Password);
 string UserName { get; }
 string Password { get; }
 }

The next step is to go ahead and implement the interface in the required platform. We will be covering Android Platform in this example.

class AuthService : IAuthService
 {
 public string Password
 {
 get
 {
 var account = AccountStore.Create(Application.Context).FindAccountsForService(Application.Context.ApplicationInfo.Name).FirstOrDefault();
 return (account != null) ? account.Properties["Password"] : null;
 }
 }
 public string UserName
 {
 get
 {
 var account = AccountStore.Create(Application.Context).FindAccountsForService(Application.Context.ApplicationInfo.Name).FirstOrDefault();
 return (account != null) ? account.Username : null;
 }
 }
 public void SaveCredentials(string UserName, string Password)
 {
 if (!string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrWhiteSpace(Password))
 {
 Account account = new Account
 {
 Username = UserName
 };
 account.Properties.Add("Password", Password);
 AccountStore.Create(Application.Context).Save(account, Application.Context.ApplicationInfo.Name);
 }
 }
 }

Do not forget to register your implementation with DependencyService by decorating the namespace with Dependency Attribute.

[assembly: Xamarin.Forms.Dependency(typeof(AuthService))]

That’s it, now you can go ahead and use it in your class in the Xamarin.Form PCL.

var AuthService = DependencyService.Get<IAuthService>();
AuthService.SaveCredentials(EmailID, Password);