Thursday, November 17, 2016

NancyFX: Stateless Auth Example

An Update...

Some time ago, I did an example of using JWTs with Nancy. This post is an update to that. It shows a lighter way of consuming JWTs with a Nancy service. The example solution is hosted on Github.

This example uses the following libraries:
  • Nancy
  • Nancy.Hosting.Aspnet
  • Nancy.Authentication.Stateless
  • JWT.
The test project adds the following libraries:
  • FakeItEasy
  • NBuilder
  • FluentAssertions
  • Nancy.Testing
A Word on JWTs

JWTs are one of the token formats that are quite common today. The site has a pretty good introductory page on them. The short story is they are a compact way to securely move information between parties (to paraphrase the site).

The Bootstrap Class

I'll start with the Nancy Bootstrap class. This class initializes the stateless authentication when the application is started. It gets an instance of the stateless authentication configuration, and enables it with a call to StatelessAuthentication.Enable(pipelines, configuration);.

Verifying The Token

The StatelessAuthConfigurationFactory returns a configuration used in the previous step. It contains the steps used to verify the JWT is valid. This is done by ensuring the issuer and audience are correct, checking if the token has expired, and if the user is valid.

Securing the Endpoint

The last bit part of the process is securing the endpoint(s). Nancy has a number of extension methods to help with this. The Health module will respond to any call with an OK status. It's not a great way to report the health of a service, but it demonstrates the idea.

The Secure module demonstrates a few ways to use the extension methods. What's really cool is the requirements can be placed at the module level as well as the endpoint level. There are two endpoints in the example: /secure and /needsclaim. Both endpoints require the call use SSL and be made with a valid JWT. The /needsclaim endpoint further requires the authenticated user be an administrator.

The End

That's the basics for getting started with stateless authentication and Nancy.