Supporting Single Sign On In Your Nancy Applications

In enterprise application the requirement for single sign on is common: Users are already authenticated against the domain controller - they don't want to jump through another authentication hoop to get access to your particular application. Setting this up in ASP.NET using WIF is some pretty easy web.config gymnastics and described elsewhere. The result of this setup is that the current principal on authenticated requests is a ClaimsPrincipal identifying the user in terms of the claims setup for him/her in the identity provided (e.g. your organizations Active Directory).
Below I show how to integrate the WIF authentication setup with your Nancy application - It doesn't take much, but lets run through it anyway. In fact only 2 small classes are needed. First we define a user type that implements the IUserIndentity interface expected by Nancy, by pulling the necessary information out of the current claims principal:

The second thing we need is set the current user on the NancyContext for each incoming request. We do this by hooking into Nancys request pipeline with a Before hook. We can do this directly in our Nancy applications bootstrapper or in a separate type implementing IApplicationStartup (Nancy automatically finds and executes these at application startup). This is how it's done with the IApplicationStartup approach:

That's it. Now your modules can start using the Context.CurrentUser and take advantage of Nancys authorization helpers.

Update: As kindly pointed out by Damian Hickey this will not work if you host your Nancy application on OWIN. So to be clear: I have only tested this when hosting on ASP.NET. The fact that it will not work on OWIN, means that the approach has the drawback that it leaks knowledge of the host to the application level. Specifically to the SetUser class.

"This post was aggregated from https://www.horsdal-consult.dk/2013/10/supporting-single-sign-on-in-your-nancy.html and all comments should be submitted on the original post"