Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NancyFx and Windows Authentication

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).

like image 562
PPC-Coder Avatar asked Nov 16 '12 19:11

PPC-Coder


People also ask

How does Windows authentication work in Web API?

Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.

How do I use Windows authentication on a web application?

On the taskbar, click Start, and then click Control Panel. In Control Panel, click Programs and Features, and then click Turn Windows Features on or off. Expand Internet Information Services, then World Wide Web Services, then Security. Select Windows Authentication, and then click OK.

How do I enable Windows Authentication in Visual Studio?

Right-click the project in Solution Explorer and select Properties. Select the Debug tab. Clear the checkbox for Enable Anonymous Authentication. Select the checkbox for Enable Windows Authentication.


3 Answers

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
like image 144
CodeFox Avatar answered Sep 23 '22 12:09

CodeFox


I needed Windows Authentication with Nancy for a basic intranet application. I used @Steven Robbins answer as a starting point, but stripped away things we didn't need and then added population of the NancyContext.CurrentUser property.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using Nancy;
using Nancy.Security;

namespace YourNamespace
{
    /// <summary>
    /// Extensions for Nancy that implement Windows Authentication.
    /// </summary>
    public static class WindowsAuthenticationExtensions
    {
        private class WindowsUserIdentity : IUserIdentity
        {
            private string _userName;

            public WindowsUserIdentity(string userName)
            {
                _userName = userName;
            }

            #region IUserIdentity

            IEnumerable<string> IUserIdentity.Claims
            {
                get { throw new NotImplementedException(); }
            }

            string IUserIdentity.UserName
            {
                get { return _userName; }
            }

            #endregion
        }

        #region Methods

        /// <summary>
        /// Forces the NancyModule to require a user to be Windows authenticated. Non-authenticated
        /// users will be sent HTTP 401 Unauthorized.
        /// </summary>
        /// <param name="module"></param>
        public static void RequiresWindowsAuthentication(this NancyModule module)
        {
            if (HttpContext.Current == null) 
                throw new InvalidOperationException("An HttpContext is required. Ensure that this application is running under IIS.");

            module.Before.AddItemToEndOfPipeline(
                new PipelineItem<Func<NancyContext, Response>>(
                    "RequiresWindowsAuthentication",
                    context =>
                    {
                        var principal = GetPrincipal();

                        if (principal == null || !principal.Identity.IsAuthenticated)
                        {
                            return HttpStatusCode.Unauthorized;
                        }

                        context.CurrentUser = new WindowsUserIdentity(principal.Identity.Name);

                        return null;
                    }));
        }

        private static IPrincipal GetPrincipal()
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.User;
            }

            return new WindowsPrincipal(WindowsIdentity.GetCurrent());
        }

        #endregion

    }
}

You use it like this:

public class YourModule : NancyModule
{
    public YourModule()
    {
        this.RequiresWindowsAuthentication();

        Get["/"] = parameters =>
            {
                //...
            };
    }

}

like image 34
John Mills Avatar answered Sep 23 '22 12:09

John Mills


I used this in an internal project recently - I don't really like it, and it ties you to asp.net hosting, but it did the job:

namespace Blah.App.Security
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Principal;
    using System.Web;

    using Nancy;

    public static class SecurityExtensions
    {
        public static string CurrentUser
        {
            get
            {
                return GetIdentity().Identity.Name;
            }
        }

        public static bool HasRoles(params string[] roles)
        {
            if (HttpContext.Current != null && HttpContext.Current.Request.IsLocal)
            {
                return true;
            }

            var identity = GetIdentity();

            return !roles.Any(role => !identity.IsInRole(role));
        }

        public static void RequiresWindowsAuthentication(this NancyModule module)
        {
            if (HttpContext.Current != null && HttpContext.Current.Request.IsLocal)
            {
                return;
            }

            module.Before.AddItemToEndOfPipeline(
                new PipelineItem<Func<NancyContext, Response>>(
                    "RequiresWindowsAuthentication",
                    ctx =>
                        {
                            var identity = GetIdentity();

                            if (identity == null || !identity.Identity.IsAuthenticated)
                            {
                                return HttpStatusCode.Forbidden;
                            }

                            return null;
                        }));
        }

        public static void RequiresWindowsRoles(this NancyModule module, params string[] roles)
        {
            if (HttpContext.Current != null && HttpContext.Current.Request.IsLocal)
            {
                return;
            }

            module.RequiresWindowsAuthentication();

            module.Before.AddItemToEndOfPipeline(new PipelineItem<Func<NancyContext, Response>>("RequiresWindowsRoles", GetCheckRolesFunction(roles)));
        }

        private static Func<NancyContext, Response> GetCheckRolesFunction(IEnumerable<string> roles)
        {
            return ctx =>
                {
                    var identity = GetIdentity();

                    if (roles.Any(role => !identity.IsInRole(role)))
                    {
                        return HttpStatusCode.Forbidden;
                    }

                    return null;
                };
        }

        private static IPrincipal GetIdentity()
        {
            if (System.Web.HttpContext.Current != null)
            {
                return System.Web.HttpContext.Current.User;
            }

            return new WindowsPrincipal(WindowsIdentity.GetCurrent());
        }

        public static Func<NancyContext, Response> RequireGroupForEdit(string group)
        {
            return ctx =>
                {
                    if (ctx.Request.Method == "GET")
                    {
                        return null;
                    }

                    return HasRoles(group) ? null : (Response)HttpStatusCode.Forbidden;
                };
        }
    }
}

It bypasses all the security checks if it's coming from local (for testing), which is probably a bad idea, but it's a behind the firewall thing so it isn't an issue for this.

Wouldn't suggest you use it verbatim, but might point you in the right direction :)

like image 20
Steven Robbins Avatar answered Sep 23 '22 12:09

Steven Robbins