问题描述
我想用NancyFx用于内部网的网络应用程序。所有的文档和论坛只提及形式和基本身份验证。任何人都成功地使用南希使用Windows身份验证?
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?
还有一种叫做Nancy.Authentication.Stateless,但我看不到有什么,做(看起来像它在API使用)。
There's also something called Nancy.Authentication.Stateless but I can't see what that does (looks like it's for use in Apis).
推荐答案
我在一个内部项目中使用这个最近 - 我真的不喜欢它,它关系到你的ASP.NET托管,但它做的工作:
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 :)
这篇关于NancyFx和Windows身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!