Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the user token in Azure Mobile App for Xamarin Forms?

I'm working on a Xamarin Forms App with .NET background for Azure Mobile App. I'm having some issues with the client and I'm wondering how should I handle the user token, the MobileServiceUser.

How should I keep the data of the token and use it through the client application?

I logged successfully the user. Now the user moves on to another page and tries to retrieve information. I created a manager like "TodoItemManager" for every table/object. So now I'm using the FoodItemManager but the MobileServiceUser of the MobileServiceClient is null because I logged the user with the LoginItemManager. So the data is lost. Should I use one manager for the entirely application to keep the MobileServiceUser alive? What's the best approach?

Thank you very much.

like image 379
Ángel Javier Mena Espinosa Avatar asked Mar 11 '23 16:03

Ángel Javier Mena Espinosa


2 Answers

You should use a singleton MobileServiceClient object for your entire app, which will retain the logged in user across all of your views. It's generally a bad idea to create a multiple client objects.

If you also want to persist the user token across app restarts, you can use the Xamarin.Auth library, which will store the token securely. Here's a sample for Xamarin.Forms: https://github.com/azure-appservice-samples/ContosoMoments/blob/master/src/Mobile/ContosoMoments/Helpers/AuthStore.cs.

like image 96
lindydonna Avatar answered Mar 30 '23 00:03

lindydonna


There are different approaches and best practices depending on what you want to achieve. If the user shall re-authenticate every time the app gets started, one can create a singleton class which holds the authentication properties. I had choosen the name "AzureData" because of your topic.

Example:

using System;

public class AzureData
{
   private static AzureDatainstance;

   private AzureData() {}

   public static AzureDataInstance
   {
      get 
      {
         if (instance == null)
         {
            instance = new AzureData();
         }
         return instance;
      }
   }

   public string MobileServiceUser { get; set; }

}

Now in your code where you determine the MobileServiceUser you perform a call like this:

AzureData.AzureDatainstance.MobileServiceUser = <yourUser>;

You can then access the content at each location of your application that has visibility to the class AzureData.

If you want to store the data in a way to survice an application restart, you need to consider other ways to store the data. Depending on the size of the data, one can use the local storage that each platform provides (e.g. NSUserDefaults for iOS) or you create files or use a local database.

like image 29
eX0du5 Avatar answered Mar 30 '23 00:03

eX0du5