NancyFx and Windows Authentication

PPC-Coder picture PPC-Coder · Nov 16, 2012 · Viewed 7.2k times · Source

I want to use NancyFx for an intranet web app. All the documentation and forums only mention Forms and Basic authentication. Anyone successfully use Nancy with Windows Authentication?

There's also something called Nancy.Authentication.Stateless but I can't see what that does (looks like it's for use in Apis).

Answer

CodeFox picture CodeFox · Oct 2, 2014

Using Nancy with WindowsAuthentication is discussed by this thread. Damian Hickey has provided an example of using Nancy, hosted by OWin with WindowsAuthentication.

I have slightly modified the code (to remove the now deprecated NancyOwinHost):

namespace ConsoleApplication1
{
    using System;
    using System.Net;
    using System.Security.Principal;
    using Microsoft.Owin.Hosting;
    using Nancy;
    using Nancy.Owin;
    using Owin;

    internal static class Program
    {
        private static void Main(string[] args)
        {
            using (WebApp.Start<Startup>("http://localhost:9000"))
            {
                Console.WriteLine("Press any key to quit.");
                Console.ReadKey();
            }
        }
    }

    internal sealed class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var listener = (HttpListener) app.Properties["System.Net.HttpListener"];
            listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

            app.UseNancy();
        }
    }

    public sealed class MyModule : NancyModule
    {
        public MyModule()
        {
            Get[""] = _ =>
            {
                var env = this.Context.GetOwinEnvironment();
                var user = (IPrincipal) env["server.User"];

                return "Hello " + user.Identity.Name;
            };
        }
    }
}

Special thanks go to Damian!


The example requires the following NuGet packages:

  • Microsoft.Owin.Host.HttpListener
  • Microsoft.Owin.Hosting
  • Microsoft.Owin
  • Nancy
  • Nancy.Owin
  • Owin