Authentication 每个路由的NancyFx身份验证
根据我在源代码中看到的情况,requireAuthentication()对整个模块进行身份验证检查。每条路线都有这样做的方法吗?我也有同样的问题。然而,Authentication 每个路由的NancyFx身份验证,authentication,routes,nancy,Authentication,Routes,Nancy,根据我在源代码中看到的情况,requireAuthentication()对整个模块进行身份验证检查。每条路线都有这样做的方法吗?我也有同样的问题。然而,requireauthentication在模块级和路由级都有效。为了演示,这里有一些从我当前项目中删除的代码(为了简洁起见,并没有显示所有路线) 当然,这样做的唯一问题是模块中所有受保护的路由都需要调用requireauthentication。在我上面的模块中,我还有另外5条路由(未显示),所有路由都需要保护,这样就可以对requireau
requireauthentication
在模块级和路由级都有效。为了演示,这里有一些从我当前项目中删除的代码(为了简洁起见,并没有显示所有路线)
当然,这样做的唯一问题是模块中所有受保护的路由都需要调用requireauthentication
。在我上面的模块中,我还有另外5条路由(未显示),所有路由都需要保护,这样就可以对requireauthentication
进行六次调用,而不是在模块级别进行一次调用。另一种选择是将未受保护的路由拉入另一个模块,但我的判断是,模块的激增比额外的RequireAuthentication调用更糟糕。namespace Kallist.modules{
namespace Kallist.Modules {
#region Namespaces
using System;
using Nancy;
#endregion
public static class ModuleExtensions {
#region Methods
public static Response WithAuthentication(this NancyModule module, Func<Response> executeAuthenticated) {
if ((module.Context.CurrentUser != null) && !string.IsNullOrWhiteSpace(module.Context.CurrentUser.UserName)) {
return executeAuthenticated();
}
return new Response { StatusCode = HttpStatusCode.Unauthorized };
}
#endregion
}
}
#区域名称空间
使用制度;
使用Nancy;
#端区
公共静态类模块扩展{
#区域方法
带有身份验证的公共静态响应(此NancyModule模块,Func executeAuthenticated){
if((module.Context.CurrentUser!=null)&&!string.IsNullOrWhiteSpace(module.Context.CurrentUser.UserName)){
返回executeAuthenticated();
}
返回新响应{StatusCode=HttpStatusCode.Unauthorized};
}
#端区
}
}
我遇到了同样的问题,下面是我如何解决的
var module = new MyModule();
module.AddBeforeHookOrExecute(context => null, "Requires Authentication");
_browser = new Browser(with =>
{
with.Module(module);
with.RequestStartup((container, pipelines, ctx) =>
{
ctx.CurrentUser = new User { UserId = "1234", UserName = "test"};
});
});
我现在可以在模块级别使用这个.requireAuthentication(),并运行我的单元测试。我没有尝试从路由调用requireAuthentication,因为在查看源代码后,它似乎不起作用。我已经创建了一个新的扩展方法,它对context.CurrentUser执行相同的检查,但返回bool。我已经发布了下面的代码,您可以这样使用它。WithAuthentication(()=>{/*需要经过身份验证的用户的代码*/});
var module = new MyModule();
module.AddBeforeHookOrExecute(context => null, "Requires Authentication");
_browser = new Browser(with =>
{
with.Module(module);
with.RequestStartup((container, pipelines, ctx) =>
{
ctx.CurrentUser = new User { UserId = "1234", UserName = "test"};
});
});