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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With