Using Azure Functions and Document DB for Simple User Authentication

Using Azure Functions and Document DB for Simple User Authentication

Often my clients need simple, inexpensive, yet scalable solution for user management. This is especially true of clients that are startups, or are developing MVPs. Cost and scalability are important.

Facebook’s server was my go-to tool until Facebook kicked it to the curb. It has since been open sourced, but still remains somewhat of a black box. (Unless you want to learn a new framework.) Now that Microsoft has added Azure Functions to its lineup, there is something simplier to set up.

With Azure, it is easy to implement a simple authentication system that uses best practices for passwords and hashing, and the creation of JWTs.   Azure Functions are Microsoft’s answer to AWS Lambda. Like AWS lambda, Azure Functions are serverless pieces of functionality triggered by a customizable variety of things. You are charged by the amount of memory in GB/sec for the time consumed by each individual action.

“HTTP triggers” are a REST endpoint that executes a specific Azure Function. There are other kinds of triggers such as queue events and timers. This post will focus on HTTP triggers.

Azure Functions are built on top of Azure Web API, but each function is in a separate directory. Azure function supports multiple languages, such as C#, python, PHP, JavaScript and others. I opted to use C #, as that is my language of choice.

An Azure Function

There are a couple configuration files in each directory which let Azure Functions know several things related to each function. In the case of HTTP triggers, this includes the REST route and security on the function.

Files in an Azure Function directory.


Though Azure Functions supports debugging, they don’t yet support unit testing. To make it easier to test this project, I put the bulk of the functionality into a shared assembly. The Azure function calls into the shared assembly which parses parameters, delegates to sub-components and formats the output. This allows me to quickly develop and debug the basic functionality. Additionally, it should be compatible with Azure Web Api projects, though I haven’t tested it yet.

Simple Authentication

This simple authentication has 3 HTTP methods: Register, Login and GetCurrentUser. The first two methods are straightforward. GetCurrentUser is there to show how to validate the java script web token (JWT).

For data storage I decided to use Microsoft’s NOSQL solution DocumentDB. DocumentDB’ s pricing model is based on reserved units of processing and max storage size. (Check for more pricing details.)

This project uses a simple abstraction for database access to facilitate mocking for unit tests, and to allow a way to use another database. The functions are very thin wrappers around calls into the shared assembly which coerce values, validate input, catch errors and return results accordingly.

There are three layers. Layer one coerces parameters from HttpRequestMessage objects and formats the HttpResponseMessage. It calls into an object that does the bulk of the work but has no awareness of http request or response messages. Finally, there is a database abstraction layer, which is concerned with finding User objects based on ID, email address or email validation code, and saving the user objects.

Creating a User

I followed best practices by using hashed passwords and user specific salt values. Additionally, I decided to use JSON Web tokens that can be passed into API calls for when the user is authenticated.

User registration simply becomes a matter of making sure the normalized email address is unused/unique, initializing the salt value, and then hashing the password storing it. I used code from here (reference) to store the hashed password. The hashed password and the salt are stripped from the user data when returned from a function. At this point I do not issue a token, because in the future I will require email validation.

Authenticating a User

User authentication takes an email address and a password. The user record that corresponds to the email address is retrieved, and the attempted password is hashed using the salt from the record. If the hash value and the hashed password in the user record match, then I return an HTTP 200, a sanitized user record, and the JWT. The JWT is non-standard right now and simply contains a creation date and expiration date, and the ID of the authenticated user.

If the two hashed values do not match, and HTTP code of 401 (unauthorized). It is considered best practice to give no indication if it is the email or the pastor that is incorrect so that they would be hacker cannot test for valid emails.

Verifying the User Authentication

If there are other Azure Functions that require the authenticated users, the JWT needs to be passed in. To check it, it needs to be unwrapped, the signature tested, and the expiration time checked against the current time. If the signature is incorrect, or the expiration time is passed then an HTTP 401 would be returned.

Of note: JWT is what is as known a bearer token. This means that no matter where this token comes from it is considered good. Some people add the hashed IP address that was used to authenticate to the token, and that is compared at the time the particular call is made. If the hashed IP address don’t match, then it is assumed that the token is invalid:

A couple notes about the code.

First, I use the JWT library from here However, the nuget package is compiled for .Net 4.6, but Azure Functions only work with .Net 4.5 as of this writing. For ease, I just copied the source in verbatim.

Second, I created some extension methods around the User object to create objects, set passwords and test password matches. Likewise, there is a helper class for JWTs called Tokens.


To make it somewhat easier to test I wrote the Azure Functions to work as either a GET or POST. That way I can simply use a browser and type in the correct values in that URL and press enter and observe the results.

Here is the response indented.

Next Steps

There are several things I will add over time:

  • Controlling what gets returned from the GetCurrentUser call.
  • Common UX patterns such as the onboarding process (see User Experience:  Inviting users to your Android or iOS app Part 1 and Part 2)
  • OAuth 2.0 and/or OpenId connect. Since this supports JWTs, it shouldn’t be too hard to add the extra steps that allow for OpenId connect.
  • Let’s encrypt support. There is a Microsoft Web API plugin that can do this. and since Azure Functions use Web APIs, it isn’t too hard to get it hooked up.


Three Tools to Make Your MVP Faster, More Flexible, and at a Lower Cost

Three Tools to Make Your MVP Faster, More Flexible, and at a Lower Cost

This most efficient business solution to manage risk is a Minimum Viable Product (MVP). At Salty Dog Technology we create MVP’s to test the basic functionality needed to verify solutions.

Having a MVP that includes a back-end amplifies risk beyond a stand-alone architecture. These risks fall into three common categories: cost, time and flexibility.

Cost matters.  An MVP’s costs can spiral if the back-end implementation is expensive operate or takes a lot of hours to build. Though not in plain sight, the server’s cost should not be underestimated.

Time matters.  If you go the route of building everything from scratch, it can take longer, be more error prone and require more testing. There is a lot of “plumbing” that needs to be implemented in that case.  You can miss product release goals if this is not taken into account when making development schedules.

Flexibility matters.  Building a back-end from scratch requires finding or creating a bunch of scaffolding functionality. If you use a 3rd party framework, then you bring its baggage along, which may be more trouble than it’s worth. All frameworks are built with assumptions that may, or may not be ideal for your app’s back-end. A back-end implementation that cannot easily change will incur higher costs and take more time.

There are some 3rd party back-end services you can try such as Facebook’s defunct and now open-sourced Parse Server, or Google’s Firebase. They have a vested interest in locking you into their service and libraries, and often they have tiered pricing which may not reflect your usage. This means that you may end up having to pay a lot more and have less ability to change.


A Middle Solution


At Salty Dog, we use a strategy that combines three Microsoft programs: Azure Functions, Azure DocumentDB and Xamarin.

Azure Functions:  Azure  Functions are a way of providing server functionality without actually having to create a server. You are charged for the resources when they are used, as opposed to a virtual machine which incurs ongoing costs independent of actual usage.

Azure functions are not tied to single computational resources. The more that your Azure functions are accessed, the more computational resources will be automatically applied. This allows the Azure functions smoothly scale according to application needs.

Azure functions provide a rich programming environment where the functionality can be implemented in a number of languages including C #, PHP, JavaScript, Python and others.  They can utilize third-party libraries to provide extra functionality, as well as access external resources such as databases and messaging infrastructures.

DocumentDB:   DocumentDB is a server-less, schema-less JSON document database. Document DB stores the data in hierarchical JSON documents. They are indexable by primary and secondary keys. Like Azure Functions, it scales smoothly as your needs grow.

This means that time doesn’t have to be spent creating the schema, updating the schema, making sure that all data passed conforms to the structure. All of those things take time. Purists would argue that those up-front definitions provide a higher level of quality, and they’re right. However, that purity and build-in checking comes at a cost that isn’t necessary with an MVP.

Azure provides is an SQL interface to DocumentDB that understands some aspects of JavaScript syntax. This gives you a known query language that can leverage Javascript data aspects.

Xamarin:  Xamarin provides a set of tools to build Android, iOS, and Mac OS apps using C#. Rather than writing in Java, Objective-C or Swift, you write in C#. It is compatible with a lot of existing .Net libraries that can be used directly in the applications.

There are multiple ways to use similar functionality across the platforms in a generic way. Typically this is done using an IoC or Inversion of Control, system.  This means that someone can create a GPS widget that is used the same way, down to the API level, on both Android or iOS.  Below the surface, it accesses the specific native functionality on the device. This means the code you write doesn’t have to know if it is running on Android or iOS.

Xamarin has created a cross platform user interface library called Xamarin Forms. Xamarin Forms provides a usable lowest common denominator UI with the ability to customize and enhance it. For less fancy or performance sensitive applications, such as games, it can speed up development.


The Right Building Blocks


Together, the three tools provide a solution to the main risks we identified.

Cost is saved.  Infrastructure, routing, and boilerplate are built in. A lot of the “plumbing” is in place.  Azure Functions feels like you’re working with a bigger web framework, without sacrificing flexibility.

Pricing is relative to the actual time a particular function is performing work. If one month the Azure Function is only used for an hour demo, we will only be charged for that hour. Conversely, if the month after that, we put our app in the hands of 50 potential clients and they use it heavily, the infrastructure will smoothly scale to meet their demand without any intervention on our part.

Using Xamarin for mobile development, especially Xamarin Forms, enables code reuse, since the same piece of code may be able to run on either Android or iOS. Development will not be done twice as it would have been if building native apps.

Time is saved. Apps can be developed locally, unit tested, and put on the server using common source control methods, like Git and branching.  It isn’t necessary to continually upload to the servers and test. This makes it easy to add features, find bugs and fix them. When the code is ready changes are pushed to the right branch, and then Azure Functions will execute a pull from the control panel. This allows multiple live versions that correspond to production phases such as “beta” and “development,” or whatever makes sense for our product. With Xamarin, the app can be separated into distinct parts  for testing in isolation outside of a mobile device.  This can save time in the develop, test, and fix cycle.

Flexibility is saved.  Since the interface between the application and the web server is the well-known REST standard, your app isn’t locked in because of special libraries.




Creating MVP’s for mobile need not be time consuming or require huge infrastructure investments.  Using Azure Functions, Azure DocumentDB, and Xamarin allows code to be quickly developed, unit tested, and reused. Used in conjunction, they allow you to focus on the MVP and its refinement without worrying as much about cost, development time, and flexibility.