Editor's Note: This post was originally posted in 2015 and has been updated for completeness and correctness in 2018.
Custom Authentication with Azure App Service
A lot has changed since the first version of this article and I have just updated it to reflect the latest updated and improvements. The techniques outlined in this blog are not limited to Azure Mobile Apps but can be applied to any .Net backend code running on Azure App Service.
I have introduced a new Github repository where a sample using a plain WebApi project (along with the Mobile App backend) is configured to use custom authentication.
Brief Introduction To Token AuthenticationAzure Mobile Apps uses tokens to authenticate users. Tokens are pieces of encoded data that contain information about a user. Whenever a user signs in with one of the built-in authentication mechanisms, say Facebook, a token is generated by the service that uniquely identifies the user. A token looks like this:
This token is then retrieved by the client application. The client application provides this token with every request to the service. When a service request is processed, the Mobile App service examines the supplied token and validates it - if the token is valid the request is allowed and processed; if not, you get а 401 Unauthorized error. With the latest update of Azure App Service, we can now easily issue such tokens. Armed with the ability to create tokens on demand we can now implement pretty much any authentication scenario.
Custom Authentication With Azure Mobile AppsTo demonstrate custom authentication we will implement one of the most common authentication scenarios - authentication with username and password. Here are the high-level steps for implementing our authentication scenario:
- Turn on App Service Authentication
- Add Microsoft.Azure.Mobile.Server.Login NuGet package
- Create custom authentication endpoint
- Configure service to require authentication
- Use token on client
1. Turn On App Service Authentication
App Service Authentication is the new and enhanced authentication mechanism for Azure App Service which provides new sign-in options as well as more control over the authentication process. App Service Authentication can be turned on from the Azure Portal as described in this article.
2. Add Microsoft.Azure.Mobile.Server.Login NuGet packageThis package sits at the core of the custom authentication mechanism. It contains the AppServiceLoginHandler.CreateToken method which allows us to issue authentication tokens. We will use AppServiceLoginHandler.CreateToken in the next step. Simply add this package to your service project and we are ready to go.
3. Create custom authentication endpointNow we need an endpoint that will sign users in if they have provided correct user name and password. To achieve this we create a new controller called AuthController:
This controller sits at the core of our custom authentication mechanism. Before a user can call one of our protected endpoints, he needs to call AuthController with valid username and password in order to get a token which will be used in all subsequent API calls. This controller is tasked with 3 responsibilities:
- Check if the supplied username and password are valid. Usually this step entails checking if the supplied username exists and if the supplied password matches the one in our database. The IsPasswordValid method presented here is just a dummy implementation which always returns true.
- Generated authentication token. If the supplied username and password are valid, the controller will generate a token that can be used to authenticate the respective user.
- Return token in the response.
This is the place where we use AppServiceLoginHandler.CreateToken provided by the Microsoft.Azure.Mobile.Server.Login package to create the actual token. The method requires 5 pieces of information in order to stitch together a valid token - claims, signing key, audience, issuer and lifetime.
The claims are additional pieces of information that can be stored in the token. For example, we can add information like username, email, security group, etc as claims to our token. In my particular example, we are adding a claim called Sub set to the value of the username that the token belongs to.
The signing key is a special string that is used to encrypt the token. Using the correct key is critical - if you create a token with a wrong key, the service will not be able read it and the token will not pass validation. Every Azure Mobile App instance has a unique signing key which is automatically set for you. This key will be used by the service to decode all tokens and we have to supply this same key when creating our tokens. Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY") returns that key.
There is not much to talk about the audience and the issuer parameters, they just have to match the url of your Azure Mobile Apps instance. Similarly to the signing key, if either of those does not match the correct url, the token is invalid.
The last parameter is the lifetime which dictates when a token expires. Our example creates a token that expires in 24 hours. Now we have a fully functional custom authentication controller. Let's instruct our service to require authentication for some of our APIs.
4. Configure service to require authenticationThis one is pretty straightforward and if you have already used Web API the chances are that you know how to do it. In order to secure an endpoint simply add [Authorize] to any methods or controllers that need to be protected. For example:
With this setup, the service will only allow access to the MyProtectedMethod if the client supplies a valid token with each request.
5. Use token on clientWe now have a protected API which can only be accessed by authenticated users. Before a user can access a protected resource the authentication endpoint must be called in order to receive a token. Once a token is received, it should be supplied as a HTTP header called x-zumo-auth with every request to out service.
Local Debugging With Custom Authentication
The code demonstrated here will work properly when deployed to Azure but if you run it locally you will find out that it does not. I have decided to combine all related information into a separate article that goes into detail on how Azure App Service authentication works and how you can debug it when running the code in your own development environment. Please check out my other article - Azure App Service - Local Debugging With Custom Authentication
This is how we can utilize the custom authentication capabilities provided by Azure App Service and Azure Mobile App respectively. As always, do not hesitate to post questions regarding this topic. You can download the source code of the entire Visual Studio project from here (CustomAuth-MobileApi).