How should I handle authentication with Nancy?

Byron Sommardahl picture Byron Sommardahl · Nov 16, 2011 · Viewed 14.6k times · Source

I started coding a LoginModule for Nancy, but it occurred to me that possibly I need to perform authentication a different way. Is there an accepted way of doing auth in Nancy? I am planning two projects right now: web and json service. I will need auth for both.

Answer

Christian Horsdal picture Christian Horsdal · Nov 16, 2011

As Steven writes Nancy supports basic and form auth out of the box. Have a look these two demo apps to see how to do each: https://github.com/NancyFx/Nancy/tree/master/samples/Nancy.Demo.Authentication.Forms and https://github.com/NancyFx/Nancy/tree/master/samples/Nancy.Demo.Authentication.Basic

From the second of those demos here is a module that requires auth:

namespace Nancy.Demo.Authentication.Forms
{
  using Nancy;
  using Nancy.Demo.Authentication.Forms.Models;
  using Nancy.Security;

  public class SecureModule : NancyModule
  {
    public SecureModule() : base("/secure")
    {
        this.RequiresAuthentication();

        Get["/"] = x => {
            var model = new UserModel(Context.CurrentUser.UserName);
            return View["secure.cshtml", model];
        };
    }
  }
}

and a bootstrapper snippet that sets up form auth in the request pipeline:

    protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
    {
        // At request startup we modify the request pipelines to
        // include forms authentication - passing in our now request
        // scoped user name mapper.
        //
        // The pipelines passed in here are specific to this request,
        // so we can add/remove/update items in them as we please.
        var formsAuthConfiguration =
            new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/login",
                UserMapper = requestContainer.Resolve<IUserMapper>(),
            };

        FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
    }