When I first began looking into how to authenticate calls made to our ASP.NET Web API services, I began by looking at what Azure could offer in the first instance as that is where the services are hosted. Azure offers many different authentication providers including Azure Active Directory, Microsoft accounts and social integrations such as Facebook, Twitter and Google accounts.
I decided on using JSON Web Token (JWT) as it fits with these requirements very well. You have a JSON structure which contains your claims (username, email and so on) which is then encoded into a string. This encoded string is then passed from the client application to the ASP.NET Web API services for authentication. The service then decodes the string and asserts the claims contained within. The JWT can be passed as a querystring parameter, as POST data or as an HTTP request header parameter. I decided that passing the JWT as an Authorization HTTP request header would be the ideal choice for our requirements as it is a standard HTTP header parameter.
The way it has been configured is that we have an Azure SQL table that contains a list of clients. Each client has a private key which is in fact a GUID. This private key is used to encode / decode the JSON Web Token. Although we could easily pass the private key with the HTTP request, I have decided that it is more secure to simply look up the private key instead, thus negating the need to pass the private key with each request. Each request contains the client name instead, from which we can perform a lookup of the private key. We then use this private key to decode the token.
Each call to one of our ASP.NET Web API services must contain an Authorization HTTP request header. This header must be composed of the client name and their JSON Web Token string. I have written code that extracts this information from the request and authenticates it.
The authentication code is part of our base controller class so that it can be easily re-used by all our services. If authentication passes then the Web API service request is processed as normal. If authentication fails then an appropriate HTTP response is returned in addition to the logging information that is captured to later diagnose why authentication failed.
To make testing authentication easier I have implemented an authentication controller that will enable client applications to test the authentication in isolation without having to actually make any actual requests to our services.
JSON Web Token is a very lightweight, simple and flexible authentication protocol that is supported on many different programming languages. If implementing external facing services where you have no control over the client application then it’s a perfect choice.