Using a Refresh Token to Renew an Expired Access Token for Azure Active Directory

Using a Refresh Token to Renew an Expired Access Token for Azure Active Directory

Currently my application attempts to acquire the access token silently which equates to looking to see if there is a current (ie not expired) token in the token cache. However, tokens don’t live for very long, so it’s quite likely that a token won’t be found. This unfortunately leads to a poor user experience as the user will quite often be prompted to sign in. There is an alternative, which is to use the refresh token, returned as part of initially acquiring the access token, to silently request a new access token. This of course is on the assumption that the refresh token hasn’t expired.

Here is a quick summary, as at the time of writing, of the different tokens and their expiry rules (a good explanation here):

  • Azure AD access tokens expire in 1 hour (see the expires_on attribute that is returned when acquiring an access token).
  • Refresh tokens expires in 14 days (see the refresh_token_expires_in attribute that is returned when acquiring an access token).
  • Access tokens can be refreshed using the refresh-token for a maximum period of time of 90 days, from the date that the access token was acquired by prompting the user.

The authentication logic can be amended to retrieve the list of refresh tokens, attempt to acquire token silently, followed by an attempt to acquire token via the refresh token. Failing that the user would be prompted to sign in.

var authContext = new AuthenticationContext(Configuration.Current.ADAuthority);

var tokens = authContext.Tokens();
var existing = (from t in tokens
                where t.ClientId == Configuration.Current.ADNativeClientApplicationClientId &&
                        t.Resource == Configuration.Current.MobileServiceAppIdUri
                select t).FirstOrDefault();
if (existing != null)
{
    try
    {
        var res = await authContext.AcquireTokenSilentAsync(
            Configuration.Current.MobileServiceAppIdUri,
            Configuration.Current.ADNativeClientApplicationClientId);
        if (res != null && !string.IsNullOrWhiteSpace(res.AccessToken))
        {
            return res.AccessToken;
        }
    }
    catch (Exception saex)
    {
        Debug.WriteLine(saex);
    }

    try
    {
        var res = await
            authContext.AcquireTokenByRefreshTokenAsync(existing.RefreshToken,
                Configuration.Current.ADNativeClientApplicationClientId);
        if (res != null && !string.IsNullOrWhiteSpace(res.AccessToken))
        {
            return res.AccessToken;
        }
    }
    catch (Exception saex)
    {
        Debug.WriteLine(saex);
    }

}

Azure Active Directory with Mobile Services without Prompting Every Time the Application Starts

Azure Active Directory with Mobile Services without Prompting Every Time the Application Starts

Currently, every time the application is run the user is prompted to sign into Azure Active Directory, and then the AD issued token is then used to login to Azure Mobile Service. Not only is this a pain for the user (for example if they’ve only just been in the application, to have to sign in again feels somewhat unnecessary), it also adds latency on startup as well as preventing the application from running when offline. In the next couple of posts I’ll look at a couple of techniques to consider in order to improve this sign on experience.

Firstly, it’s worth noting that there was an update posted for the Azure Active Directory Authentication library (ADAL) on NuGet – it’s still prerelease but worth updating to if you’re using v3 of the library. More info on NuGet, here.

One of the nice things about ADAL is that it provides a cache for tokens. In addition to being able to query what tokens are in the cache (for example in order to then login to the Mobile Service) it also wraps the check to determine if a token is still valid. To do this, I can call AcquireTokenSilentAsync to authenticate silently ie without prompting the user. If a valid access token is found in the token cache it will be returned. In the case that no valid token is found and exception is raised and I then need to invoke AcquireTokenAsync as I did previously.

var authContext = new AuthenticationContext(Configuration.Current.ADAuthority);
try
{
    var res = await authContext.AcquireTokenSilentAsync(
        Configuration.Current.MobileServiceAppIdUri,
        Configuration.Current.ADNativeClientApplicationClientId);
    if (res != null && !string.IsNullOrWhiteSpace(res.AccessToken))
    {
        return res.AccessToken;
    }
}
catch (Exception saex)
{
    Debug.WriteLine(saex);
}

As Windows Phone 8.0 isn’t supportedyet by v3 of ADAL, I also need to update my custom implementation of the AuthenticationContext. Firstly, to add a static list of previously acquired tokens:

private static readonly List<AuthenticationResult> Tokens = new List<AuthenticationResult>();  

Next, I need to update my AuthenticationResult option to decode more than just the access and refresh tokens:

public class AuthenticationResult
{
    private static DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime();

    public string ClientId { get; set; }

    [JsonProperty(“access_token”)]
    public string AccessToken { get; set; }

    [JsonProperty(“refresh_token”)]
    public string RefreshToken { get; set; }

    [JsonProperty(“resource”)]
    public string Resource { get; set; }

        [JsonProperty(“expires_on”)]
    public long ExpiresOnSeconds { get; set; }

    public DateTime ExpiresOn
    {
        get { return epoch.AddSeconds(ExpiresOnSeconds); }
    }

    private long refreshTokenExpiresInSeconds;
    [JsonProperty(“refresh_token_expires_in”)]
    public long RefreshTokenExpiresInSeconds
    {
        get { return refreshTokenExpiresInSeconds; }
        set
        {
            refreshTokenExpiresInSeconds = value;
            RefreshTokensExpiresOn = DateTime.Now.AddSeconds(refreshTokenExpiresInSeconds);
        }
    }

    public DateTime RefreshTokensExpiresOn { get;private set; }

}

At the end of the AcquireTokenAsync method I need to set the ClientId property on the AuthenticationResult (so I know which AAD client id it was returned for as this isn’t returned in the response) and add the result to the Tokens list:

var result = JsonConvert.DeserializeObject<AuthenticationResult>(await data.Content.ReadAsStringAsync());
result.ClientId = ClientId;
Tokens.Add(result);
return result;

Finally I need to implement the AcquireTokenSilentAsync method – although it doesn’t require async/Task I’ve kept the method consistent with ADAL to avoid conditional code when calling the method

public async Task<AuthenticationResult> AcquireTokenSilentAsync(
    string resource,
    string clientId)
{
   

    var result = (from t in Tokens
                        where t.ClientId == clientId &&
                                   t.Resource == resource &&
                                   t.ExpiresOn > DateTime.Now
                        select t).FirstOrDefault();

    return result;
}

Note that this implementation doesn’t persist the access token beyond the current session. However, it will avoid the need to reauthenticate if the user does happen to do something that would otherwise require authentication.

Custom Domains for Azure Mobile Services

Custom Domains for Azure Mobile Services

As packaging a cloud based solution one of the tasks is to change the configuration of the services so that they have a application specific domain. In the case of Azure websites this feature has been available for quite a while in the form of custom domains. However, it was only recently that this capability was added to Azure Mobile Services. This enables me to change the Mobile Service url from https://realestateinspector.azure-mobile.net to https://realestate.builttoroam.com. This capability is only available to Mobile Services running in Standard mode, which can be quite a costly commitment if custom domains are the only reason to upgrade.

Here’s a quick run through of setting up a custom domain. Note that this doesn’t include setting up SSL for your custom domain, which is highly recommended. There is more information here that includes using wildcard SSL certificates, which might be useful if you are packaging multiple services (eg Mobile Service and a Website) off the same base domain.

The first thing to do is to setup a CName record (alternatively you can setup an A record using these instructions) – this needs to be done with the name service that hosts the DNS records for your domain.

image

If you simply try to browse to the new URL you’ll see quite a useful 404 message. The first option is exactly the scenario I now face – I have to configure the Mobile Service to know about the custom domain.

image

Currently there is no UI in the Azure portal for managing custom domains for Mobile Services, unlike for Azure Websites where it can all be configured in the portal. Instead, I need to use the Azure CLI. Before doing this, make sure you are using v0.8.15 or higher (v0.8.15 is current at time of writing). Note that I ran into some issues upgrading the Azure CLI – docs online suggest using npm (eg npm update azure-cli, or npm update azure-cli –g depending on whether you installed the azure-cli globally or not). However, I found that this wasn’t working – the output suggested it had updated to 0.8.15 but when I queried azure –v I saw an earlier version. Turns out that I’d installed the azure-cli via the Web Platform Installer – in this case you either need to uninstall the azure-cli via the platform installer, or simply install the new version via the platform installer (which is what I did).
Adding a custom domain is then relatively straight forward: azure mobile domain add <mobileservicename> <customdomain> eg

image

Now when you browse to the new url you see the typical Mobile Service status homepage.

image

When I run my client applications I need to update the Mobile Service Client URL to point to the new url. I can then see in Fiddler that the traffic is indeed going to the new custom domain.

image

Database Migrations with Package Manager Console and Azure Mobile Services

Database Migrations with Package Manager Console and Azure Mobile Services

I was caught out recently after I published an incorrect database migration into my cloud base Azure Mobile Service (I created a second controller based on the RealEstateProperty entity instead of the PropertyType entity). The upshot is that I only noticed this when all the properties of the entities I was synchronizing down from the cloud came back with null for most of their properties. Initially I thought my issue was with the migration I had performed on the database, so I thought I’d roll back to a previous version. My most recent migration was “201502260615263_Added proeprty type entity” and I wanted to roll it back to the previous migration, “201501061158375_AddedInspections”. To do this you can simply call the update-database method in the Package Manager Console:

update-database –TargetMigration “201501061158375_AddedInspections”

However, I wanted to invoke this only the database for the Mobile Service running in the cloud. To do this I need to add the –ConnectionString and –ConnectionProviderName attributes. The latter is easy as it needs to be the static value “System.Data.SqlClient” but the former requires two steps:

– In the Azure Management Portal go to the SQL Databases tab and then select the database that correlates to the Mobile Service. With the database selected, click “Manage” from the toolbar – this will prompt to add a firewall rule allowing access from your computer (this only happens the first time or again if your ip address changes). You need to add this firewall rule as Visual Studio will be attaching directly to the database to run the code-first migration on the database.

image

– From the Dashboard pane of the SQL Server database, select Connection Strings from the right link menu, and copy the contents of the ADO.NET connection string.

image

Now I can add the connection string to the update-database method:

update-database –TargetMigration “201501061158375_AddedInspections” –ConnectionString “Server=tcp:p7zzqmjcmf.database.windows.net,1433;Database=realestateinspector;User ID={my username};Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;” –ConnectionProviderName “System.Data.SqlClient”

I checked that this had removed the PropertyType table (which was part of the migration I just reversed) and then removed the old migration file, “201502260615263_Added proeprty type entity.cs”, and then regenerated the new migration by calling add-migration again:

add-migration ‘Added proeprty type entity’

Given that the Mobile Service itself hadn’t changed at that point I figured that I’d simply call update-database without the TargetMigration parameter but with the ConnectionString that points to my actual Mobile Service. This seemed to go ok but then when I ran my Mobile Service and attempted to synchronize my PropertyType entities – this caused an exception because I’d discovered the root of my issue, which was I had two controllers both referencing the RealEstateProperty entity. I fixed that and republished my Mobile Service. Now synchronization worked, but mainly because there were no entities in the PropertyType table in the database, so I then attempted to add a PropertyType using the direct access (rather than synchronizing entities) in the MobileServiceClient (using GetTable instead of GetSyncTable) – this caused some weird exception as it seemed to require that the CreatedAt property be set. I’ve never had to do this on previous inserts, so I sensed something was wrong. Using the Visual Studio 2015 CTP I connected directly to the SQL Server database and sure enough on my PropertyType table there were no triggers for insert/update. Usually this is where the CreatedAt column is updated.

So, feeling a little puzzled I decided to undo my migration on my Mobile Service database once more. But this time, instead of attempting to change any of the migration scripts, all I did was republish my Mobile Service. Now when I attempted to add a PropertyType it worked, no problems. Checking with Visual Studio 2015, the trigger on the PropertyType table had been successfully created. At this point I’m not sure what exactly happens when the Mobile Service runs but it seems to do more than just applying the code-first migrations. It definitely seems to me that updating the cloud database using the package manager console seemed to skip the validation step that Mobile Services does in order to add the appropriate triggers, and thus should be avoided.

Multiple Bootstrapper in WebApiConfig for Mobile Service

Multiple Bootstrapper in WebApiConfig for Mobile Service

In my “wisdom” I decided to rename the primary assembly for my Mobile Service (ie just changing the assembly name in the Properties pane for the Mobile Service).

image

This all worked nicely when running locally but when I published to Azure I started seeing the following error in the Log, and of course my service wouldn’t run…

Error: More than one static class with name ‘WebApiConfig’ was found as bootstrapper in assemblies: RealEstateInspector.Services, realestateinspectorService. Please provide only one class or use the ‘IBootstrapper’ attribute to define a unique bootstrapper.

Turns out that when I was publishing I didn’t have the “Remove additional files at destination” box checked in the Publish Web dialog. This meant that my old Mobile Service assembly (ie with the old name) was still floating around. As reflection is used over assemblies in the bin folder to locate the bootstrapper, it was picking up the same class in both assemblies…. hence the issue.

image

Checking the “Remove additional files at destination” box ensures only those files that are currently in your Mobile Service project are deployed.

Azure Active Directory Graph API and Azure Mobile Service

Azure Active Directory Graph API and Azure Mobile Service

Last month in an earlier post I talked about using the Azure Active Directory Graph API Client library in my Azure Mobile Service. Whilst everything I wrote about does indeed when published to the cloud, it does raise a number of errors that are visible in the Log and the status of the service ends up as Critical – which is definitely something I don’t want. The error looks something like the following:

Error: Found conflicts between different versions of the same dependent assembly ‘System.Spatial’: 5.6.2.0, 5.6.3.0. Please change your project to use version ‘5.6.2.0’ which is the one currently supported by the hosting environment.

Essentially the issue is that the Graph API references a newer version of some of the data libraries (System.Spatial, Microsoft.Data.OData, Microsoft.Data.Edm and Microsoft.Data.Services.Client to be exact). What’s unfortunate is that even using the runtime redirect in the web.config file to point to the newer versions of these library which are deployed with the service, the errors still appear in the log. As there essentially doesn’t seem to be any compatibility issues between the Graph API and the slightly older version (ie 5.6.2.0) I even tried downgrading the other libraries (you can use the –Force function in package management console to remove NuGet packages even if others are dependent on them, so I removed the new versions and added the old version back in) but of course Visual Studio then fails its validation checks during compilation.

The upshot is that you have to either:

– Wait for the Mobile Services team to upgrade their backend to support the new versions of these libraries…..personally I don’t understand why this causes an error in the logs and forces the service to critical, particularly since my service actually appears to be operating fine!

– Downgrade the Graph API Library back to the most recent v1 library – this references an older version of those libraries so has now issues. Unfortunately it doesn’t contain the well factored ActiveDirectoryClient class, making it harder to query AAD.

Migrating Data Between Blob Storage Accounts in Azure

Migrating Data Between Blob Storage Accounts in Azure

Over the last couple of posts I’ve been talking about working with different configurations and in my previous post I noted that one of the things we had to do was to migrate some data that had been entered into the Test environment into Production environment (again I stress that I’m not recommending it but occasionally you have to bend the process a little). One of the challenges we encountered was that we not only had to migrate the database, which was easy using the database copy capability in the Azure portal, we also needed to migrate the related blob storage data from one account into another. Here’s some quick code that makes use of the Azure Storage client library (WindowsAzure.Storage package via NuGet and more information here).

Firstly in the app.config we have two connection strings:

<connectionStrings>
    <add name=”BlobMigrator.Properties.Settings.SourceStorage”
      connectionString=”DefaultEndpointsProtocol=https;AccountName=sourceaccount;AccountKey=YYYYYYYYYYY” />
    <add name=”BlobMigrator.Properties.Settings.TargetStorage”
      connectionString=”DefaultEndpointsProtocol=https;AccountName=targetaccount;AccountKey=XXXXXXXXXXXXXXX” />

</connectionStrings>

Next, some straight forward code to iterate through containers in one storage account and copy content across to the target account:

var source= CloudStorageAccount.Parse(Settings.Default.SourceStorage);
var target= CloudStorageAccount.Parse(Settings.Default.TargetStorage);

var sourceClient = source.CreateCloudBlobClient();
var targetClient = target.CreateCloudBlobClient();

var containers= sourceClient.ListContainers(“searchprefix”).ToArray();
Debug.WriteLine(“Source containers: ” + containers.Length);
var idx = 0;
foreach (var cnt in containers)
{
    var tcnt =targetClient.GetContainerReference(cnt.Name);
    await tcnt.CreateIfNotExistsAsync();

    var sblobs = cnt.ListBlobs();
    foreach (var sblob in sblobs)
    {
        var b = await sourceClient.GetBlobReferenceFromServerAsync(sblob.Uri);
        var tb = tcnt.GetBlockBlobReference(b.Name);
        var ok = await tb.StartCopyFromBlobAsync(b.Uri);
        Debug.WriteLine(ok);
    }
    idx++;
    Debug.WriteLine(“Migrated {0} of {1} – {2}”,idx,containers.Length,cnt.Name);
}

In this case it’s limiting the containers that are copied to those that start with the prefix “searchprefix” but this is optional if you want to copy all containers.

Different Cloud Environments for Development, Testing and Production

Different Cloud Environments for Development, Testing and Production

One of the aspects of developing applications that have a cloud backend that gets overlooked initially is how to separate development from test and production versions of the application. For web applications ASP.NET solved this by supporting transformations in the web.config file based on build configuration (eg web.Debug.config and web.Release.config). However, this issue is harder with client applications that don’t have config files and don’t understand configuration transformations. The other issue with transformations is that they’re only applied during the publishing process, rather than simply when you change the build configuration in Visual Studio.

I’ll come back to talk about how I’ve chosen to handle different application configurations in a later post. In this post I want to discuss how we’ve handled having multiple environments for our Mobile Service backend; this includes how we decided to do this working with our development team v’s the client site.

Our strategy was to have three environments: Development, Testing and Production. Development was housed within the Built to Roam development Azure subscription which the development team have access to. For the most part anyone within the development team could deploy to this environment at any stage – of course there was some self management involved to minimize breaking changes. As an aside, as I’ve pointed out in a previous post, it is possible to set up Mobile Services to run locally, even if you enable Azure Active Directory authentication. The Development environment was also based on an Azure Active Directory (AAD) tenant explicitly created for the development of that project – that way accounts could be added/removed without affecting any other AAD.

Test and Production were both created in the customers Azure subscription. This was to minimize differences between these environments. These environments also connected to the customers AAD which meant that testing could be carried out with real user accounts since their AAD was synchronized with their internal AD. In a case where writing is supported back to AAD you may want to consider having test pointing to a separate AAD instance but for our purposes AAD was read only so there was no issue in using the same AAD tenant for both Test and Production.

For each of these we created a separate Mobile Service, named according to the environment, with production being the exception as we decided to drop the “production” suffix. Taking the RealEstateInspector example our services would be called:

Development – RealEstateInspectorDev
Testing – RealEstateInspectorTest
Production – RealEstateInspector

Note that we shortened both Development and Testing to just Dev and Test for simplicity.

We also created corresponding storage accounts, with names that matched the names of the mobile service

We also created corresponding applications in the appropriate Azure Active Directory, again with names that matched the corresponding environment. We didn’t use the same applications for Testing and Production to ensure we could configure them separately if required.

One issue we faced is that during the first iteration of development as the system was undergoing final testing in the Testing environment some real data was entered into the system. This meant that rather than simply deploying to Production we actually needed to migrate data from Testing to Production (definitely not something I would recommend as best practice). To do this was actually relatively simple using the ability in Azure to copy a SQL database and then within the Mobile Service change the database that it points to. We also had to migrate content from one storage account to another for which we couldn’t find a simple out of the box tool to use. However, this was actually much simpler than we thought and I’ll come back to this in a future post.

Integration Synchronization Wrapper and Restructuring Application Services

Integration Synchronization Wrapper and Restructuring Application Services

So far all the Mobile Service operations, including holding the instance of the MobileServiceClient, has been done by the MainViewModel. Clearly as the application grows this is not a viable solution so we need some application services which can be used to hold the reference to the MobileServiceClient and to facilitate application logic such as data access and synchronisation. To this end I’m going to create two services, IDataService and ISyncService with their corresponding implementations as follows:

public interface IDataService
{
    IMobileServiceClient MobileService { get; }

    Task Initialize(string aadAccessToken);
}

public class DataService: IDataService
{
    private readonly MobileServiceClient mobileService = new MobileServiceClient(
        Constants.MobileServiceRootUri,
        “wpxaIplpeXtkn——QEBcg12”,
        new MobileServiceHttpHandler()
        );

    public IMobileServiceClient MobileService
    {
        get { return mobileService; }
    }

    public async Task Initialize(string aadAccessToken)
    {
        var jobj = new JObject();
        jobj[“access_token”] = aadAccessToken;
        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 CustomMobileServiceSyncHandler());

    }
}

The IDataService implementation holds the reference to the IMoblieServiceClient. This will need to be initialized by passing in the Azure Active Directory access token but there after the MobileService accessor can be used to access data directly through the IMobileServiceClient instance.

public interface ISyncService
{
    event EventHandler<DualParameterEventArgs<double, string>> Progress;
    Task Synchronise(bool waitForCompletion);
    Task ForceUpload();
}

public class SyncService: ISyncService
{
    [Flags]
    private enum SyncStages
    {
        None = 0,
        UploadChanges = 1,
        PullProperties = 2,
        PullInspections = 4,
        All = UploadChanges | PullProperties | PullInspections
    }

    public event EventHandler<DualParameterEventArgs<double,string>> Progress;

    public IDataService DataService { get; set; }

    private ISynchronizationContext<SyncStages> SynchronizationManager { get; set; }

    public SyncService(IDataService dataService)
    {
        DataService = dataService;
        SynchronizationManager = new SynchronizationContext<SyncStages>();
        SynchronizationManager.DefineSynchronizationStep(SyncStages.UploadChanges, UploadPendingLocalChanges);
        SynchronizationManager.DefineSynchronizationStep(SyncStages.PullProperties, DownloadChangesToRealEstateProperties);
        SynchronizationManager.DefineSynchronizationStep(SyncStages.PullInspections, DownloadChangesToInspections);
        SynchronizationManager.SynchronizationChanged += SynchronizationManager_SynchronizationProgressChanged;
    }

    public async Task Synchronise(bool waitForCompletion)
    {
        await SynchronizationManager.Synchronize(SyncStages.All, waitForSynchronizationToComplete: waitForCompletion);
    }

    public async Task ForceUpload()
    {
        await SynchronizationManager.Synchronize(SyncStages.UploadChanges, true, true);
    }

    private void SynchronizationManager_SynchronizationProgressChanged(object sender, SynchronizationEventArgs<SyncStages> e)
    {
        var message = e.ToString();
        if (Progress != null)
        {
            Progress(this,new object[]{ e.PercentageComplete, message});
        }
    }

    private async Task<bool> UploadPendingLocalChanges(ISynchronizationStage<SyncStages> stage)
    {
        await DataService.MobileService.SyncContext.PushAsync(stage.CancellationToken);
        return true;
    }
    private async Task<bool> DownloadChangesToRealEstateProperties(ISynchronizationStage<SyncStages> stage)
    {
        await DataService.MobileService.PullLatestAsync<RealEstateProperty>(stage.CancellationToken);
        return true;
    }
    private async Task<bool> DownloadChangesToInspections(ISynchronizationStage<SyncStages> stage)
    {
        await DataService.MobileService.PullLatestAsync<Inspection>(stage.CancellationToken);
        return true;
    }
}

The ISyncService defines the actual synchronization steps. Rather than simply exposing a generic Synchronize method that accepts the a SyncStages parameter to determine which steps are synchronized, the ISyncService actually exposes high level methods for performing a full synchronize (Synchronize) and just to upload pending changes (ForceUpload). Note that the former has a parameter indicating whether the method should wait synchronization completion before returning, whereas the latter will always wait for the upload part of the synchronize to complete.

To make these services available to the view models of the application the BaseViewModel has been updated to include properties for both services:

public class BaseViewModel : INotifyPropertyChanged
{
    public IDataService DataService { get; set; }
    public ISyncService SyncService { get; set; }

And of course the ViewModelLocator is updated to create instances of these services and assign them to the view model when they’re created:

public class ViewModelLocator
{
    public IDataService DataService { get; set; }
    public ISyncService SyncService { get; set; }

    public ViewModelLocator()
    {
        DataService=new DataService();
        SyncService=new SyncService(DataService);
    }

    public MainViewModel Main
    {
        get { return CreateViewModel<MainViewModel>(); }
    }

    private readonly Dictionary<Type, object> viewModels = new Dictionary<Type, object>();

    private T CreateViewModel<T>() where T:new()
    {
        var type = typeof (T);
        object existing;
        if (!viewModels.TryGetValue(type, out existing))
        {
            existing = new T();
            viewModels[type] = existing;
        }

        var baseVM = existing as BaseViewModel;
        if (baseVM != null)
        {
            baseVM.DataService = DataService;
            baseVM.SyncService = SyncService;
        }

        return (T)existing;
    }
}

Fixing up the Client For Writing to Azure Blob Storage with Shared Access Signature

Fixing up the Client For Writing to Azure Blob Storage with Shared Access Signature

In my previous post I updated the service logic for retrieving the Shared Access Signature (SAS) to return the full Url of the blob container including the SAS. In order for this to work I also need to update the client logic. This gets much simpler as I can simply construct a new CloudBlockBlob by amending the Url to include the name of the blob to be written to.

private async void CaptureClick(object sender, RoutedEventArgs e)
{
    var picker = new MediaPicker();
    var sas = string.Empty;
    using (var media = await picker.PickPhotoAsync())
    using (var strm = media.GetStream())
    {
        sas = await CurrentViewModel.RetrieveSharedAccessSignature();

        // Append the image file name to the Path (this will
        // retain the SAS as it’s in the query string
        var builder = new UriBuilder(sas);
        builder.Path += “/testimage” + Path.GetExtension(media.Path);
        var imageUri = builder.Uri;

        // Upload the new image as a BLOB from the stream.
        var blob = new CloudBlockBlob(imageUri);
        await blob.UploadFromStreamAsync(strm.AsInputStream());
    }
}

But, we can actually do even better…. what we get back is a Url, including the SAS, for the blob container. So we can use the Azure Storage library to create a CloudBlobContainer and then acquire the blob reference from there – this does the work of combining the urls for us.

private async void CaptureClick(object sender, RoutedEventArgs e)
{
    var picker = new MediaPicker();
    var sas = string.Empty;
    using (var media = await picker.PickPhotoAsync())
    using (var strm = media.GetStream())
    {
        sas = await CurrentViewModel.RetrieveSharedAccessSignature();
        var container = new CloudBlobContainer(new Uri(sas));
        var blobFromContainer = container.GetBlockBlobReference(“testimage” + Path.GetExtension(media.Path));
        await blobFromContainer.UploadFromStreamAsync(strm.AsInputStream());
    }
}

Modifying the GET Request for the SharedAccesSignature Controller

Modifying the GET Request for the SharedAccesSignature Controller

In the previous post I noted that the code was pretty messy, particularly for the client code with a bunch of hardcoded literals. To fix this I’m going to encapsulate the full URL for blob storage into the server code, meaning that the client shouldn’t have to know the url of blob storage – this will make it easy to administer this in the future as things change.

It turns out that in order to make this change all I needed to do is to return the full blob container url (including the SAS) instead of just the SAS.

var ub = new UriBuilder(container.Uri.OriginalString)
{
    Query = container.GetSharedAccessSignature(sasPolicy).TrimStart(‘?’)
};
sas =  ub.Uri.OriginalString;

The client code of course needs to be updated to handle the full Uri being passed back – Note that we didn’t include the name of the blob as part of creating the Uri. This is something the client should do. Since the SAS is for access to the whole container, the client doesn’t have to request a new SAS for each blob, only for each container it wants to write to.

Saving Image to Blob Storage Using Shared Access Signature

Saving Image to Blob Storage Using Shared Access Signature

In this post I’m  going to bring together a couple of my previous posts that discuss retrieving and saving images, and retrieving a Shared Access Signature from a controller which will allow me to write to a particular container within Blob Storage. To complete the implementation I’ll use the Windows Azure Storage library from NuGet – it only installs for Windows platforms as there’s no PCKL or Xamarin support for this library currently.

image

As the Windows Azure Storage library is current platform specific, I’ll need to wrap it in a simple interface that makes it easy for me to write data to Blob Storage – I’ll come back to that. For the time being I’m just going to retrieve the SAS and use it along with the storage library to upload an image. So I’ll start by invoking the sharedaccesssignature controller using the GET verb as I want to ensure the container is created if it doesn’t already exist. This will return a SAS which I can use in the upload process.

public async Task<string> RetrieveSharedAccessSignature()
{
    var sas = await MobileService.InvokeApiAsync<string>(“sharedaccesssignature”, HttpMethod.Get,
        new Dictionary<string, string> { { “id”, “test” } });
    return sas;
}

Next I want to capture an image, in this case picking a photo, and uploading it to a specified blobg.

private async void CaptureClick(object sender, RoutedEventArgs e)
{
    var picker = new MediaPicker();
    var sas = string.Empty;
    using (var media = await picker.PickPhotoAsync())
    using (var strm = media.GetStream())
    {
        sas = await CurrentViewModel.RetrieveSharedAccessSignature();

        Debug.WriteLine(sas);

        // Get the URI generated that contains the SAS
        // and extract the storage credentials.
        var cred = new StorageCredentials(sas);
        var imageUri = new Uri(“
https://realestateinspector.blob.core.windows.net/test/testimage.png”);

        // Instantiate a Blob store container based on the info in the returned item.
        var container = new CloudBlobContainer(
            new Uri(string.Format(“
https://{0}/{1}”,
                imageUri.Host, “test”)), cred);

        // Upload the new image as a BLOB from the stream.
        var blobFromSASCredential = container.GetBlockBlobReference(“testimage.png”);
        await blobFromSASCredential.UploadFromStreamAsync(strm.AsInputStream());
    }

}

Clearly this code isn’t well factored but it’s here as a quick example of how you can use a SAS to upload content to blob storage.

Simplifying Shared Access Signature Generation with the Mobile Services ResourceBroker

Simplifying Shared Access Signature Generation with the Mobile Services ResourceBroker

In my post Storing the Big Stuff in Blob Storage I showed you how to manually create a shared access signature. The Azure Mobile Services team have done a really nice job of making this even easier with the ResourceBroker NuGet package. Getting started documentation is available via GitHub (https://github.com/Azure/azure-mobile-services-resourcebroker) and of course the package, which I’ve added to my Mobile Service project, is available via NuGet.

image

The changes I needed to make to my SharedAccessSignature controller are:

– Change my Web.config to include the ResourceBrokerStorageConnectionString appSetting – the documentation talks about adding this via the Configure panel of the mobile service portal but you’ll need to add it to web.config for debugging. Also the format of this string should be similar to the following:

<add key=”ResourceBrokerStorageConnectionString”
     value=”DefaultEndpointsProtocol=https;AccountName=realestateinspector;AccountKey=LxWu0q2UvQ7ddxXvIP3UfV4ozDkLpgaSkUxkK8————————–BYHTpTrAGaHjLoynH+61ng==” />

– Change the base class of the controller to ResourcesControllerBase (I needed to add an import statement to the top of the file too)

– Add routing information to the WebApiConfig.cs file (as per the documentation on GitHub)

// Create a custom route mapping the resource type into the URI.    
var resourcesRoute = config.Routes.CreateRoute(
     routeTemplate: “api/resources/{type}”,
     defaults: new { controller = “resources” },
     constraints: null);

// Insert the ResourcesController route at the top of the collection to avoid conflicting with predefined routes.
config.Routes.Insert(0, “Resources”, resourcesRoute);

– Initially I removed the contents of my controller but then I realised that there are limitations on the ResourceControllerBase (eg the Blob container must exist and that I needed to specify an actual blob, not just a container for access), so I kept my code and modified it to work with the new connection string.

public class SharedAccessSignatureController :  ResourcesControllerBase
{
    public async Task<string> Get(string id)
    {
        var sas = string.Empty;

        if (!string.IsNullOrEmpty(id))
        {
            // Try to get the Azure storage account token from app settings. 
            string storageAccountConnectionString;

            if (Services.Settings.TryGetValue(“ResourceBrokerStorageConnectionString”, out storageAccountConnectionString) )
            {
                // Set the URI for the Blob Storage service.
                var account = CloudStorageAccount.Parse(storageAccountConnectionString);
                // Create the BLOB service client.
                var blobClient = new CloudBlobClient(account.BlobStorageUri,account.Credentials);

                // Create a container, if it doesn’t already exist.
                var container = blobClient.GetContainerReference(id);
                await container.CreateIfNotExistsAsync();

                // Create a shared access permission policy.
                var containerPermissions = new BlobContainerPermissions();

                // Enable anonymous read access to BLOBs.
                containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
                container.SetPermissions(containerPermissions);

                // Define a policy that gives write access to the container for 1h
                var sasPolicy = new SharedAccessBlobPolicy()
                {
                    SharedAccessStartTime = DateTime.UtcNow,
                    SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(59).AddSeconds(59),
                    Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
                };

                sas = container.GetSharedAccessSignature(sasPolicy);
            }
        }

        return sas;
    }
}

– To get my code to work I also had to amend the route to the following, adding the id as an optional parameter

var resourcesRoute = config.Routes.CreateRoute(
        routeTemplate: “api/sharedaccesssignature/{type}/{id}”,
        defaults: new { controller = “sharedaccesssignature”, id = RouteParameter.Optional },
        constraints: null);

Calling the controller from Fiddler can be done in two ways:

GET: http://localhost:51539/api/sharedaccesssignature/blob/test

POST: http://localhost:51539/api/sharedaccesssignature/blob
Content-Type: application/json
{
    “name”: “myblob”,
    “container”: “test”,
    “permissions”: “w”,
    “expiry”: “2015-12-01T07:34:42Z”
}

Don’t forget that if during debugging you set authenticationlevel to anonymous, to make sure you change it back to User or Application before publishing.

Storing the Big Stuff in Blob Storage

Storing the Big Stuff in Blob Storage

Often mobile applications need to store and retrieve large object data, typically photos and video. This is where Azure blog storage comes into play. In order to write into blob storage you need an access key. However, you’d never distribute an actual access key out to a mobile application, even temporarily, as it’s a really bad idea – if someone gets hold of the access key they have access to everything stored in your blob storage. Luckily blob storage has the notion of shared access signatures which you can think of as short term access passes to blob storage. These are typically created using a full access key and as such this operation is done service side.

I’m going to create a dedicated API just for granting shared access signatures to specific containers (which you can think of as single level folders). In this case the containers will be created with public read access on the contents – since the list of blobs per container will be protected and clients will still need a shared access signature in order to write to containers, this should be ample security for a large proportion of application scenarios.

I’ll start off by creating a new Storage area within the Azure management portal.

image

Once created you’ll need to record the storage account name (realestateinspector) and the storage account access key. Add these values into the appSettings section of the web.config file for the Azure Mobile Service

<appSettings>

  <add key=”STORAGE_ACCOUNT_NAME”
       value=”realestateinspector” />
  <add key=”STORAGE_ACCOUNT_ACCESS_KEY”
       value=”LxWu0q2UvQ7ddxXvIP3UfV4ozDkLpgaSkUx————————————33WBYHTpTrAGaHjLoynH+61ng==” />

I’ll create a new controller in my Azure Mobile Service based on the Custom Controller item template

image

The bulk of this api controller sits within a single GET operation:

[AuthorizeLevel(AuthorizationLevel.User)]
public class SharedAccessSignatureController : ApiController
{
    public ApiServices Services { get; set; }

    public async Task<string> Get(string containerToAccess)
    {
        var sas = string.Empty;

        if (!string.IsNullOrEmpty(containerToAccess))
        {
            // Try to get the Azure storage account token from app settings. 
            string storageAccountName;
            string storageAccountKey;

            if (Services.Settings.TryGetValue(“STORAGE_ACCOUNT_NAME”, out storageAccountName) &&
                Services.Settings.TryGetValue(“STORAGE_ACCOUNT_ACCESS_KEY”, out storageAccountKey))
            {
                // Set the URI for the Blob Storage service.
                var blobEndpoint = new Uri(string.Format(“
https://{0}.blob.core.windows.net”, storageAccountName));

                // Create the BLOB service client.
                var blobClient = new CloudBlobClient(blobEndpoint, new StorageCredentials(storageAccountName, storageAccountKey));

                // Create a container, if it doesn’t already exist.
                var container = blobClient.GetContainerReference(containerToAccess);
                await container.CreateIfNotExistsAsync();

                // Create a shared access permission policy.
                var containerPermissions = new BlobContainerPermissions();

                // Enable anonymous read access to BLOBs.
                containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
                container.SetPermissions(containerPermissions);

                // Define a policy that gives write access to the container for 1h
                var sasPolicy = new SharedAccessBlobPolicy()
                {
                    SharedAccessStartTime = DateTime.UtcNow,
                    SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(59).AddSeconds(59),
                    Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read
                };

                sas = container.GetSharedAccessSignature(sasPolicy);
            }
        }

        return sas;
    }
}

If you change the AuthorizationLevel to Anonymous you can run up this controller and use Fiddler to generate the shared access signature by invoking a GET on (eg http://localhost:51539/api/SharedAccessSignature/test, where test is the name of the container we’re requesting access to. If you want to check that the container has been created and the appropriate security set, you can use the CloudBerry Explorer for Azure Blob Storage.

image

After entering credentials you can immediately see the folders in your blob storage which will in this case have the container “test” which was created when I made the request to the SharedAccessSignature service.

image

You can also use Fiddler to prepare and launch a query – don’t forget to switch the AuthorizationLevel back to User before deploying your services otherwise anyone will be able to access content from your blob storage.

Long Running Azure Mobile Service Call With Feedback using SignalR

Long Running Azure Mobile Service Call With Feedback using SignalR

I’ve been thinking a little more about alternative mechanisms for sending feedback to the client applications when a long running mobile service call is executing. In my previous post on Long Running Custom API Calls in Azure Mobile Service I discussed returning immediately to the client application whilst continuing to process a long running task. Unfortunately this means there is no way to provide feedback. In this post I’m going to add in SignalR to provide that real time communications link.

 

 

image

I’ll define a class that in herits from Hub and exposes a Services property – this will be populated automatically by the Mobile Service.

public class LongRunningFeedbackHub : Hub
{
    public ApiServices Services { get; set; }
}

Next I’ll amend the Get service method to a) take a parameter (which is the connection id of signalr on the client) and b) provide feedback during the long running task via the hub object. Note the use of the dynamic Progress method which will correlate to the client side proxy method that it subscribes to.

public async Task<string> Get(string id)
{
    var host = new ReportHost();
    host.DoWork(async (cancel) =>
    {
        try
        {
            var hub = Services.GetRealtime<LongRunningFeedbackHub>();

            var max = 5;
            for (int i = 0; i < max; i++)
            {
                await Task.Delay(TimeSpan.FromSeconds(5), cancel);

                hub.Clients.
                    Client(id)
                    .Progress(string.Format(“{0}% complete”,100*i/5));
            }
        }
        catch (Exception ex)
        {
            // Don’t bubble the exception – do something sensible here!
            Debug.WriteLine(ex.Message);
        }
    });
    Services.Log.Info(“Hello from custom controller!”);
    return “Hello”;
}

I added the initialization logic for the SignalR to the Register method of the WebApiConfig.cs file, as well as providing an explicit route to support the id parameter

config.Routes.MapHttpRoute(
    name: “DefaultApi”,
    routeTemplate: “api/{controller}/{action}/{id}”,
    defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);

SignalRExtensionConfig.Initialize();

On the client side I add the SignalR .NET Client library from NuGet

image

And then add a ConnectToSignalR method to establish the hub connection and return a connectionId, which will then be passed into the view model via the GenerateReport method.

private async void GenerateReportClick(object sender, RoutedEventArgs e)
{
    var connectionId=await  ConnectToSignalR();
    CurrentViewModel.GenerateReport(connectionId);
}

private async Task<string> ConnectToSignalR()
{
    var hubConnection = new HubConnection(MainViewModel.MobileService.ApplicationUri.AbsoluteUri);
    //if (user != null)
    //{
    //    hubConnection.Headers[“x-zumo-auth”] = user.MobileServiceAuthenticationToken;
    //}
    //else
    //{
    hubConnection.Headers[“x-zumo-application”] = MainViewModel.MobileService.ApplicationKey;
    //}
    IHubProxy proxy = hubConnection.CreateHubProxy(“LongRunningFeedbackHub”);
    await hubConnection.Start();

    //string result = await proxy.Invoke<string>(“Send”, “Hello World!”);
    //var invokeDialog = new MessageDialog(result);
    //await invokeDialog.ShowAsync();

    proxy.On<string>(“Progress”,
        msg => Debug.WriteLine(msg));

    return hubConnection.ConnectionId;
}

The only change to the GenerateReport method is for it to accept an id parameter and for this parameter to be passed into the custom api

var result = await MobileService.InvokeApiAsync<string>(“Reporter”, HttpMethod.Get, new Dictionary<string, string>{{“id”,connectionId}});

When this is run and the GenerateReport method is invoked, the current percentage complete is passed back to the client and appears in the handler for the Progress message.

Long Running Custom API Calls in Azure Mobile Service

Long Running Custom API Calls in Azure Mobile Service

As I pointed out in my previous post a common scenario for custom apis in a Mobile Service is to hand off tasks that aren’t easily done on a mobile device, or are better suited to being done server side (eg report creation). Quite often these tasks can take longer than the default timeout of most service requests (typically 60seconds) which means the mobile app ends up raising an exception which is not very useful. A better approach is to queue the work somehow and then to periodically check on it’s progress. In this post I’m just going to demonstrate one way to allow the service to respond immediately, whilst continuing to carry out the task in the background. Note that the ReportHost is based on the JobHost class described in Phil Haack’s post on the dangers of background tasks

public async Task<string> Get()
{
    var host = new ReportHost();
    host.DoWork(async (cancel) =>
    {
        try
        {
            await Task.Delay(TimeSpan.FromMinutes(2), cancel);
        }
        catch (Exception ex)
        {
            // Don’t bubble the exception – do something sensible here!
            Debug.WriteLine(ex.Message);
        }
    });
    Services.Log.Info(“Hello from custom controller!”);
    return “Hello”;
}

And the ReportHost class

public class ReportHost : IRegisteredObject
{
    private readonly ManualResetEvent reportLock = new ManualResetEvent(false);
    private readonly CancellationTokenSource cancellation=new CancellationTokenSource();

    public ReportHost()
    {
        HostingEnvironment.RegisterObject(this);
    }

    public void Stop(bool immediate)
    {
        cancellation.Cancel();
        reportLock.WaitOne();
        HostingEnvironment.UnregisterObject(this);
    }

    public void DoWork(Func<CancellationToken,Task> work)
    {
        Task.Run(async () =>
        {
            await work(cancellation.Token);
            reportLock.Set();
        });
    }
}

I haven’t shown any client side code for the timebeing because it remains the same (although it won’t timeout now!). The next step is to provide some way that the client can check on the progress of the work item.

Invoking a Custom API in Azure Mobile Service

Invoking a Custom API in Azure Mobile Service

The full scenario is that we have a task that needs to be performed by the Mobile Service that might take a while to complete. The first step is to define a custom api which will invoke the task (alternatively you could hijack a table controller to launch the task as part of one of the CRUD actions) and to have this called from the client applications. However, this alone is not sufficient for long running tasks as the call to the service may timeout before the task completes. I’ll come back to that in a future post but for now, let’s look at creating a custom api.

The first step is to add a new controller based on the Microsoft Azure Mobile Services Custom Controller template.

image

I’ll give the new controller a name

image

For the time being the only change I’ll make is to include the AutorizeLevel and AuthorizeInspector attributes to enforce the security policies required for accessing our services:

[AuthorizeLevel(AuthorizationLevel.User)]
[AuthorizeInspector]
public class ReporterController : ApiController
{
    public ApiServices Services { get; set; }

    // GET api/Reporter
    public async Task<string> Get()
    {
        Services.Log.Info(“Hello from custom controller!”);
        return “Hello”;
    }

}

Invoking this from the client can easily be done from within the MainViewModel:

public async void GenerateReport()
{
    string message;
    try
    {
        var result = await MobileService.InvokeApiAsync<string>(“Reporter”, HttpMethod.Get, null);
        message = result;
    }
    catch (MobileServiceInvalidOperationException ex)
    {
        message = ex.Message;
    }
    Debug.WriteLine(message);
}

Easy done – a simple api that we can invoke within our Mobile Service to do work. Note that in this case it’s a Get requrest with no parameters and a simple string return type. We can adjust this to be a Post, accept parameters and return a complex object by adjusting both the controller method definition (ie change Get to Post, or even just add a Post method) and invokeapiasync call.

Handling MobileServiceConflictException with Azure Mobile Service with Offline Sync

Handling MobileServiceConflictException with Azure Mobile Service with Offline Sync

Whenever you do offline sync, there is a risk of conflicts emerging between client and server updates. Of course the data architecture should be done to minimise this (eg guid based primary keys) but this won’t always eliminate the issue. One example of where this might happen is if the client gets cut off midway through pushing changes to the server. For example if I were to insert a new record on the client, push the changes but before the changes had been confirmed back to the client, the network connection was terminated. The server now has the new record but the client thinks it still needs to send the record – when it does, a conflict arises where both server and client have records with the same primary key. Let’s replicate this and then look at solving it.

I’ll create an AddProperty method into my MainViewModel:

public async Task AddProperty()
{
    var table=MobileService.GetSyncTable<RealEstateProperty>();
    var prop = new RealEstateProperty
    {
        Address = “New Random Property”
    };
    await table.InsertAsync(prop);
    await MobileService.SyncContext.PushAsync();
}

Run this, and insert a breakpoint after the InsertAsync but before the PushAsync. At this point inspect the prop object and retrieve the Id. Next, using either Sql Server Management Studio or Visual Studio 2015, connect to the SQL Server instance and run the following query (replacing the Id with the one retrieved in previous step).

insert into realestateinspector.RealEstateProperties (Id,Address,Deleted) Select ‘0a1f8994-4a4b-4548-921a-4da0186b3f6c’,’Not created on client’,0

Now, if I let the PushAsync continue it will fail, causing an exception to be raised.

image

There are a couple of places that this can be handled. The first is where the call to PushAsync is made – this isn’t great as pushing to the remove service won’t necessarily happen at this point. For example you might insert a record but not push immediately. In this case when you next issue a pull request the push will be done prior to doing the pull. A better way to handle it is to supply a custom MobileServiceSyncHandler as part of the initialization of the sync context:

 

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

The sync handler could look like the following (this is very basic and just drops any conflicts)

public class CustomMobileServiceSyncHandler : MobileServiceSyncHandler
{
    public async override Task<JObject> ExecuteTableOperationAsync(IMobileServiceTableOperation operation)
    {
        try
        {
            return await base.ExecuteTableOperationAsync(operation);
        }
        catch (MobileServiceConflictException cex)
        {
            Debug.WriteLine(cex.Message);
            throw;
        }
    }

    public override Task OnPushCompleteAsync(MobileServicePushCompletionResult result)
    {
        foreach (var error in result.Errors)
        {
            if (error.Status == HttpStatusCode.Conflict)
            {
                error.CancelAndUpdateItemAsync(error.Result);
                error.Handled = true;
            }
        }
        return base.OnPushCompleteAsync(result);
    }
}

Restricting Access to Azure Mobile Service Base on Azure Active Directory Group

Restricting Access to Azure Mobile Service Base on Azure Active Directory Group

In my previous post I controlled access to the GetAll method on my base controller by determining whether the authenticated (from AAD) user was a member of the Inspectors AAD group. This is actually quite a slow process and not something you really want to do every session. Ideally I’d like this check to be done once when the user authenticates against the mobile service (which happens after they authenticate against AAD) and for the IsInspector claim to be added to the user identity. Unfortunately for the life of me I can’t work out how to force OWIN into accepting an additional claim – I’m sure there’s a way, but I ended up settling for an alternative approach.

My approach actually improves on two aspects over what I was previously doing. The first is that I implement the checking logic as an attribute which can then be applied to the root controller. The second is that by storing a cookie in the response, I can reduce the need to re-query AAD for the group membership. This solution is based on a couple of great blog posts:

http://www.acupofcode.com/2014/04/general-roles-based-access-control-in-the-net-backend/

http://www.acupofcode.com/2014/03/roles-based-access-control-in-mobile-services-and-azure-active-directory/

The AuthorizeInspector attribute looks as follows:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class AuthorizeInspector : AuthorizationFilterAttribute
{
    public static ActiveDirectoryClient RetrieveActiveDirectoryClient(string token)
    {
        var baseServiceUri = new Uri(Microsoft.Azure.ActiveDirectory.GraphClient.Constants.ResourceId);
        var activeDirectoryClient =
            new ActiveDirectoryClient(new Uri(baseServiceUri, Constants.ADTenant),
                async () => token);
        return activeDirectoryClient;
    }

    public async override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        await base.OnAuthorizationAsync(actionContext, cancellationToken);

        var cookie = HttpContext.Current.Request.Cookies[“IsInspector”];
        var isInspector = cookie != null ? cookie.Value : null;
        if (isInspector != null)
        {
            if (!(bool.Parse(isInspector)))
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
            }
            return;
        }

        var controller = actionContext.ControllerContext.Controller as ApiController;
        if (controller == null)
        {
            return;
        }
        var user = controller.User as ServiceUser;

        //var user = User as ServiceUser;
        var aadCreds = (await user.GetIdentitiesAsync()).OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
        Debug.WriteLine(aadCreds.AccessToken);

        var token = actionContext.Request.Headers.GetValues(Constants.RefreshTokenHeaderKey)
            .FirstOrDefault();

        var auth = new AuthenticationContext(Constants.ADAuthority, false);
        var newToken = await auth.AcquireTokenByRefreshTokenAsync(token,
                Constants.ADNativeClientApplicationClientId, “
https://graph.windows.net”);

        var client = RetrieveActiveDirectoryClient(newToken.AccessToken);
        var grps = await client.Groups.ExecuteAsync();
        var moreGroups = grps.CurrentPage;

        while (moreGroups != null)
        {
            foreach (var grp in grps.CurrentPage)
            {
                if (grp.DisplayName == “Inspectors”)
                {
                    if ((await client.IsMemberOfAsync(grp.ObjectId, aadCreds.ObjectId)) ?? false)
                    {
                        HttpContext.Current.Response.Cookies.Add(new HttpCookie(“IsInspector”, true.ToString()));

                        return;
                    }
                }
            }
            if (grps.MorePagesAvailable)
            {
                grps = await grps.GetNextPageAsync();
                moreGroups = grps.CurrentPage;
            }
            else
            {
                grps = null;
                moreGroups = null;
            }
        }
        HttpContext.Current.Response.Cookies.Add(new HttpCookie(“IsInspector”, false.ToString()));
    }
}

As you can see this follows roughly the same logic for querying AAD group membership. However, this time I’m adding a cookie based on whether the user is an Inspector or not.This attribute can now be applied to the RealEstateBaseTableController.

[AuthorizeInspector]
public class RealEstateBaseTableController<TEntity> : TableController<TEntity>
    where TEntity : class, ITableData
{

One thing to be aware of is that this cookie will persist even if the user logs out. As such, we need some way of associating the cookie with the current user session. It may be that an additional cookie is used to associate the access token with the IsInspector cookie. For example:

public override async Task OnAuthorizationAsync(HttpActionContext actionContext,
    CancellationToken cancellationToken)
{
    await base.OnAuthorizationAsync(actionContext, cancellationToken);

    var controller = actionContext.ControllerContext.Controller as ApiController;
    if (controller == null)
    {
        return;
    }
    var user = controller.User as ServiceUser;

    //var user = User as ServiceUser;
    var aadCreds = (await user.GetIdentitiesAsync()).OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
    Debug.WriteLine(aadCreds.AccessToken);

    var cookie = HttpContext.Current.Request.Cookies[“IsInspector”];
    var isInspector = cookie != null ? cookie.Value : null;
    var accessTokenCookie = HttpContext.Current.Request.Cookies[“IsInspectorAccessToken”];
    var access_token = accessTokenCookie != null ? accessTokenCookie.Value : null;
    if (isInspector != null && access_token == aadCreds.AccessToken)
    {
        if (!(bool.Parse(isInspector)))
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
        }
        return;
    }

    var token = actionContext.Request.Headers.GetValues(Constants.RefreshTokenHeaderKey)
        .FirstOrDefault();

    var auth = new AuthenticationContext(Constants.ADAuthority, false);
    var newToken = await auth.AcquireTokenByRefreshTokenAsync(token,
        Constants.ADNativeClientApplicationClientId, “
https://graph.windows.net”);

    var client = RetrieveActiveDirectoryClient(newToken.AccessToken);
    var grps = await client.Groups.ExecuteAsync();
    var moreGroups = grps.CurrentPage;

    try
    {
        while (moreGroups != null)
        {
            foreach (var grp in grps.CurrentPage)
            {
                if (grp.DisplayName == “Inspectors”)
                {
                    if ((await client.IsMemberOfAsync(grp.ObjectId, aadCreds.ObjectId)) ?? false)
                    {
                        HttpContext.Current.Response.Cookies.Add(new HttpCookie(“IsInspector”, true.ToString()));

                        return;
                    }
                }
            }
            if (grps.MorePagesAvailable)
            {
                grps = await grps.GetNextPageAsync();
                moreGroups = grps.CurrentPage;
            }
            else
            {
                grps = null;
                moreGroups = null;
            }
        }
        HttpContext.Current.Response.Cookies.Add(new HttpCookie(“IsInspector”, false.ToString()));
    }
    finally
    {
        HttpContext.Current.Response.Cookies.Add(new HttpCookie(“IsInspectorAccessToken”, aadCreds.AccessToken));

    }
}

Augmenting Mobile Service Response with Azure Active Directory Group Membership

Augmenting Mobile Service Response with Azure Active Directory Group Membership

In the previous post we saw how you can query Azure Active Directory after authenticating a Mobile Service client against Azure Active Directory. Now I’m going to use this knowledge to restrict access to data based on group membership. In this case the user has to belong to a group with the name “Inspectors”. One thing you’ll notice is that this process is quite slow, so we’ll have to look for a better way to enforce security, without having to query AAD with each service request. The full GetAll method is as follows:

public async Task<IQueryable<TEntity>> GetAll()
{
    var user = User as ServiceUser;
    var aadCreds = (await user.GetIdentitiesAsync()).OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
    Debug.WriteLine(aadCreds.AccessToken);

    var token = this.ActionContext.Request.Headers.GetValues(Constants.RefreshTokenHeaderKey)
        .FirstOrDefault();

    var auth = new AuthenticationContext(Constants.ADAuthority, false);
    var newToken = await auth.AcquireTokenByRefreshTokenAsync(token,
        Constants.ADNativeClientApplicationClientId, “
https://graph.windows.net”);

    var client = RetrieveActiveDirectoryClient(newToken.AccessToken);
    var grps = await client.Groups.ExecuteAsync();
    var moreGroups = grps.CurrentPage;
    while (moreGroups != null)
    {
        foreach (var grp in grps.CurrentPage)
        {
            if (grp.DisplayName == “Inspectors”)
            {
                if ((await client.IsMemberOfAsync(grp.ObjectId, aadCreds.ObjectId)) ?? false)
                {
                    return Query();
                }
            }
            Debug.WriteLine(grp != null);
        }
        if (grps.MorePagesAvailable)
        {
            grps = await grps.GetNextPageAsync();
            moreGroups = grps.CurrentPage;
        }
    }

    return null;
}