Accessing Authentication Required Mobile Service

Accessing Authentication Required Mobile Service

Previously I added security to my mobile service by Requiring Authentication on the Azure Mobile Service and in my previous post I showed how you can manually request an authorization and access token. In addition to exploring the id_token (which is the unassigned JWT) if you explore the access_token you can see that it has a claim pertaining to the Mobile Service

image

We’re going to use this value to authenticate against our Mobile Service, which will allow us to query the data. In my MainViewModel I’m going to adjust the code slightly to use this access token value – this is just to demonstrate how the access token is going to be used, of course in a real world application you’ll need to authenticate the user using a web browser in the application in order to retrieve the access_token, but more on that later. My LoadPropertyData method now looks like this (the access_token value has been shortened to make the code more readable but was copied directly from the response in fiddler:

public async Task LoadPropertyData()
{
    var access_token=”eyJ0eXAiOiJKV1Qi———TOF9eYN97Jey-r_oDq5anQ”;
    var jobj = new JObject();
    jobj[“access_token”] = access_token;
    var access = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, jobj);
    Debug.WriteLine(access!=null);
    var data = new MobileServiceSQLiteStore(“inspections.db”);
    data.DefineTable<RealEstateProperty>();
    data.DefineTable<Inspection>();

    await MobileService.SyncContext.InitializeAsync(data, new MobileServiceSyncHandler());

    await MobileService.PullLatestAsync<RealEstateProperty>();
    await MobileService.PullLatestAsync<Inspection>();

    var props = await MobileService.GetSyncTable<RealEstateProperty>().ToListAsync();
    foreach (var prop in props)
    {
        Properties.Add(prop);
    }
}

This code can be run and will retrieve the properties in the Mobile Service, at least whilst the access_token remains valid

Leave a Reply

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