Xamarin forms WebAuthenticator usage

1.3k Views Asked by At

I'm trying to implement Facebook Auth for Xamarin Forms App. I'm doing everything like in this tutorial https://learn.microsoft.com/en-us/xamarin/essentials/web-authenticator?tabs=android so I'm using server side auth. Here is my mobile app code:

   public class WebAuthViewModel:ObservableObject
    {
        private const string AuthenticationUrl = "https://myapp.com/mobileauth/";

        private string _accessToken = "";
        private bool _isAuthenticated = false;

        public string AuthToken
        {
            get => _accessToken;
            set => SetProperty(ref _accessToken, value);
        }
    
        public ICommand FacebookCommand { get; }

        public WebAuthViewModel()
        {
            FacebookCommand = new Command(async()=>await OnAuthenticate("Facebook"));
        }

        async Task OnAuthenticate(string scheme)
        {
            try
            {
                WebAuthenticatorResult result = null;

                var authUrl = new Uri(AuthenticationUrl + scheme);
                var callbackUrl = new Uri("myapp://");
                result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);
                
                AuthToken = string.Empty;

                if (result.Properties.TryGetValue("name", out var name) && !string.IsNullOrEmpty(name))
                {
                    AuthToken += $"Name: {name}{Environment.NewLine}";
                }

                if (result.Properties.TryGetValue("email", out var email) && !string.IsNullOrEmpty(email))
                {
                    AuthToken += $"Email: {email}{Environment.NewLine}";
                }
                
                AuthToken += result?.AccessToken ?? result?.IdToken;
                IsAuthenticated = true;
            }
            catch (Exception ex)
            {
                AuthToken = string.Empty;
            }
        }
    }

Also I have some back-end code. All this works fine, I'm getting access token, UserId and so on. But I still have some questions.

What is the right way to validate if login is still valid? How should I authorize app actions? And how could I implement Logout?

I will be grateful for advices or links.

1

There are 1 best solutions below

4
On

As a user, you don’t want to have to sign in every time you use the app. Luckily, MSAL already caches your authorization and can log you in silently if it’s still valid.When properly authenticated we receive an access token that we can subsequently use to query other APIs that are secured by MSAL.

Signing out is pretty straight forward. We go through all the available accounts that MSAL has locally cached for us and sign them out. We also clear the access token that we stored in secure storage when we signed in.

public async Task<bool> SignOutAsync()
{
  try
  {
    var accounts = await _pca.GetAccountsAsync();

    // Go through all accounts and remove them.
    while (accounts.Any())
    {
        await _pca.RemoveAsync(accounts.FirstOrDefault());
        accounts = await _pca.GetAccountsAsync();
    }

    // Clear our access token from secure storage.
    SecureStorage.Remove("AccessToken");

    return true;
  }
  catch (Exception ex)
  {
    Debug.WriteLine(ex.ToString());
    return false;
  }
}