Xamarin store login credentials

I had created a login form using Xamarin Forms this makes a http post to a REST api. Returning the users ID.

Logging in can be a pain, so I was looking for a way to securely store the login credentials once the user has been authenticated. Xamarin.Auth has a feature to allow this. It can also handle the auth aspects, but I had this covered already.

Nuget the Xamarin.Auth package.

Create a static class

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Xamarin.Auth;

namespace MyAppMobile.Classes
{
  public static class MyAccountStore
    {
        private const string AppName = "MyApp";

        public static 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().Save(account, AppName);
            }
        }

        public static string UserName
        {
            get
            {
                var account = AccountStore.Create().FindAccountsForService(AppName).FirstOrDefault();
                return (account != null) ? account.Username : null;
            }
        }

        public static string Password
        {
            get
            {
                var account = AccountStore.Create().FindAccountsForService(AppName).FirstOrDefault();
                return (account != null) ? account.Properties["Password"] : null;
            }
        }
    }
}

There is currently a bug in the package. Android requires a Nuget package PCL Crypto.
Install this into the Android project only (currently 2.0.147 is working for me with Xamarin.Auth 1.5.0.3)

On the initial login you can now store the credentials with

MyAccountStore.SaveCredentials(email, password);

Now when the ViewModel is initialised you can retrieve the previous username and password, hit the login API and if successful, log the user in.

The next challenge is to store the UserId so that I can use it in subsequent api requests.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.