我想将NancyFx用于Intranet Web应用程序。所有文档和论坛都仅提及表单和基本身份验证。任何人都可以通过Windows身份验证成功使用Nancy吗?
还有一个叫做Nancy.Authentication.Stateless的东西,但是我看不到它的作用(看起来像是在Apis中使用的)。
最佳答案
我最近在一个内部项目中使用了它-我真的不喜欢它,它使您与asp.net托管联系起来,但是它确实做到了:
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;
};
}
}
}
如果它来自本地(用于测试),它将绕过所有安全检查,这可能不是一个好主意,但这是防火墙背后的事情,因此这不是问题。
不建议您一字不漏地使用它,但可能会指出正确的方向:)
关于asp.net - NancyFx和Windows身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13423239/