Using Azure App Service Authentication with a Web Application

My pet project is an ExpressJS application with a React/Flux front-end running on top of Azure App Service. Since I will want to use Azure Mobile Apps to provide a common UI between a mobile edition of the app and the web edition of the app, I want to use the built-in Authentication feature to handle the authentication. Here is the question. I’ve got built-in mechanisms in the Azure Mobile Apps SDKs to handle authentication properly – how do I do this in the Web App? It’s not complicated, but the documentation is not where it should be. In this blog post, I’ll walk you through the process of using Azure App Service Authentication in a React web app.

For the purposes of this blog post, I’m going to assume you have already set up Authentication and have a good mechanism for deploying your app to Azure App Service. If you haven’t, check out:

The Web Version

My first stab at this is to look at the process that my web application has to go through. Firstly, it has to redirect to /.auth/login/provider on your site. Im using the Microsoft Login as my authentication as it’s really easy to set up. You might want to do Facebook, Twitter, Google or AAD instead. The URL is

Once I’m sent there, the Azure App Service will redirect to the identity provider (Microsoft in this case), then come back and give you a “Redirect back to Website”. Click on that and your home page is reloaded. This time there is a new cookie. Unfortunately, you can’t access it:


That check mark under HTTP means that the JavaScript can’t access the cookie. Some other mechanism is required. Fortunately, Azure App Service has provided such an endpoint – /.auth/me. This endpoint will give a JSON document that contains the token plus some other information:


The endpoint returns a 401 Unauthorized status if the user is not logged in.

The JavaScript Version

My application has an app-store.js that implements a Flux store. This is a store with my own design, but you could easily use Redux, Alt or Fluxxor, for example. In the constructor, I register an action handler and then dispatch the action to the action handler:

        // Register any action listeners
        this.logger.debug('Creating Dispatch Table');
        this.onActionDispatched('init-store', (payload) => { this.initializeStore(payload); });
        this.onActionDispatched('check-auth', (payload) => { this.checkAuthentication(payload); });

        // Dispatch initial actions
        this.logger.debug('Dispatching Store Initializer');
        dispatcher.dispatch({ actionType: 'init-store' });
        dispatcher.dispatch({ actionType: 'check-auth' });

Line 37 registered the action handler and then line 42 dispatches the action. Once someone loads the app store, the action handler will be called. On to the action handler. I use the fetch API to actually do the request:

     * Action Handler for the check-auth event
     * @param {Object} payload the payload provided to the dispatcher
     * @returns {boolean} true if the payload was handled
    checkAuthentication(payload) {
        this.logger.entry('checkAuthentication', payload);

        this.logger.debug(`Initiating fetch of /.auth/me`);
        let options = {
            method: 'GET',
            credentials: 'include',
            cache: 'no-cache'

        // Fetch the authentication configuration
        fetch('/.auth/me', options).then((response) => {
            this.logger.debug('[checkauth-callback-1]: Response = ', response);
            if (!response.ok && response.status !== 401)
                throw new Error('Invalid Response from Config Endpoint', response);
            if (response.status === 401)
                return false;
            return response.json();
        }).then((config) => {
            if (!config) {
      '[checkauth-callback-2] unauthenticated');
            this.logger.debug('[checkauth-callback-2]: config = ', config);
            this.storeData.error = false;
        }).catch((error) => {
            this.logger.error(`[checkauth-callback-catch] failed to check authentication status`);
            this.storeData.error = { message: error.message };

        return this.logger.exit('checkAuthentication', true);

This doesn’t actually store any data – that depends on your application. Line 112 (highlighted) will log whatever is in the returned JSON object:


It’s worth taking a look at the return value and decoding it. In my application, I need to load up the object with the information I received. I’m going to convert the object that is returned into a set of claims:


To do this, I’m going to use Array.reduce – a JavaScript function that takes a little bit of time to even understand, let alone master. It works across an array, calling the function with an accumulator. In my case, the accumulator is an empty object and the function converts the key/value pairs present in the response into object notation. Here is the code:

             * Map/Reduce mapper for dealing with claims
             * @param {object} target the target object
             * @param {object} claim each individual claim
             * @returns {object} the target
            function mapClaims(target, claim) {
                target[claim.typ] = claim.val;
                if (claim.typ.indexOf('') !== -1)
                    target[claim.typ.slice(claim.typ.lastIndexOf('/') + 1)] = claim.val;
                return target;

            let providerData = auth[0];
            this.storeData.auth = {
                claims: providerData.user_claims.reduce(mapClaims, {}),
                id: providerData.user_id,
                provider: providerData.provider_name,
                token: providerData.access_token,
                providertoken: providerData.authentication_token
            this.logger.debug('[checkauth-callback-2]: authdata = ', this.storeData.auth);

Finishing Up

What else is needed? When I login, I need to redirect the page to the /.auth/login/microsoftaccount – I’m using a standard React event handler for this in my Chrome.jsx file. The click handler then sets document.location to the required value. I’m also going to adjust my user card – I have the users real name now, so I want to represent that.

I need to figure out logging out of Azure App Service. Logging out is not implemented in the SDKs, so I’m going to have to do some research.

The other thing I need to do is to sort out the offline development model. I have to deploy this application to Azure to do little tests. I will sometimes alter a file in numerous small ways, running the resulting code several times before I am satisfied. The Azure App Service deployment process takes six minutes. That is just way too long for the development cycle. As a result, I’m going to look at mocking the /.auth endpoint in development.

As always, check out the code on my GitHub Repository.