Skip to content

Instantly share code, notes, and snippets.

@damianh
Created April 8, 2014 03:10
Show Gist options
  • Save damianh/10086352 to your computer and use it in GitHub Desktop.
Save damianh/10086352 to your computer and use it in GitHub Desktop.
Nancy owin self hosting with Microsoft.Owin.HttpListener and windows authentication on .NET 4.0 (Personal opinion: avoid windows NTLM auth in web applications, even intranet ones. Use standards based SSO.)
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Principal;
using Microsoft.Owin.Hosting;
using Nancy;
using Owin;
internal class Program
{
private static void Main(string[] args)
{
using (WebApp.Start<Startup>("http://localhost:9000"))
{
Console.WriteLine("Press Enter to quit.");
Console.ReadKey();
}
}
}
internal class Startup
{
public void Configuration(IAppBuilder app)
{
var listener = (HttpListener) app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
app.UseNancy();
}
}
public class MyModule : NancyModule
{
public MyModule()
{
Get[""] = _ =>
{
var env = ((IDictionary<string, object>) Context.Items[Nancy.Owin.NancyOwinHost.RequestEnvironmentKey]);
var user = (IPrincipal) env["server.User"];
return "Hello " + user.Identity.Name;
};
}
}
}
@Cruelio
Copy link

Cruelio commented Oct 15, 2014

Which nuget packages and version does this code use. I have tried with
Microsoft.Owin.Hosting 3.0.0
Microsoft.Owin 3.0.0
Nancy 0.23.2
OWIN 1.0

I get the following error when compiling.
Owin.IAppBuilder' does not contain a definition for 'UseNancy'

@brendan-nobadthing
Copy link

@Cruelio from here: https://github.com/NancyFx/Nancy/wiki/Hosting-nancy-with-owin I think your missing package is:
Nancy.Owin

@BanksySan
Copy link

Hi,

Thanks for the code snippet.

When I run this in Nancy.Owin 1.4.1 it give a compile error The type or namespace name 'NancyOwinHost' does not exist in the namespace 'Nancy.Owin' (are you missing an assembly reference?).

Do you know how do I get this to work with the latest build?

Thanks

Dave

@BanksySan
Copy link

Figured it out. I wanted:

var requestEnvironment = (IDictionary<string, object>) Context.Items["OWIN_REQUEST_ENVIRONMENT"];
var user = (IPrincipal) requestEnvironment["server.User"];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment