Home > Azure, C#, Mobile Services > How to invoke Azure Mobile Services operations as admin from a client application

How to invoke Azure Mobile Services operations as admin from a client application


When we create a table or a custom API on an Azure Mobile Service, we need to specify the permissions required to access it. One of this permission is Only Scripts and Admins, meaning that the operation requires the Service Master Key, which limits the operation only to registered scripts or to administrator accounts. It provides full access to any of the Service tables and APIs, no matter their specific permissions.

However, using the Mobile Services Client SDK, we can’t execute requests as administrator, because accessing the server as admin requires a special header, that the Client SDK doesn’t allow to set. This is by design, because it isn’t recommended to embed the Master Key into an application.

That said, if we anyhow want to obtain administrator access to the Mobile Service through the client, we can create an handler that automatically adds the appropriate header to every request:

public class MasterKeyHandler : DelegatingHandler
    private string masterKey;

    public MasterKeyHandler(string masterKey)
        this.masterKey = masterKey;

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
        // Adds the Master Key to the Request's header collection.
        request.Headers.Add("X-ZUMO-MASTER", masterKey);

        // Sends the actual request to the Mobile Service.
        var response = await base.SendAsync(request, cancellationToken);
        return response;

Using a DelegatingHandler, we can delegate the processing of HTTP requests and responses to our procedure. In this case, by overriding the SendAsync method, we add an header to every request, X-ZUMO-MASTER, containing the Service Master Key.

Now we need to add this handler to the Mobile Service execution pipeline, so that it will be automatically invoked everytime we make a call to the Service. To do so, we need to use an overload of the MobileServiceClient constructor:

public static MobileServiceClient MobileService = new MobileServiceClient(
    new MasterKeyHandler("mobile_service_master_key")

The third parameter of the constructor accepts a param array of HttpMessageHandler: to use our custom processor, we simply need to create an instance of MasterKeyHandler class passing the Service Master Key to it. In this way, every request will include the X-ZUMO-MASTER header, and so, when the Service receives this value, will grant administrator access to the operation.

As already said, remember that the Master Key is an important security credential that should be used only by a service administrator, so be careful with it, because who owns the Master Key has full access to the Mobile Service data.

Categories: Azure, C#, Mobile Services
Comments are closed.
%d bloggers like this: