【发布时间】:2012-08-24 11:53:39
【问题描述】:
从我在源代码中看到的 RequiresAuthentication() 对整个模块进行身份验证检查。每条路线有什么方法可以做到这一点吗?
【问题讨论】:
标签: authentication routes nancy
从我在源代码中看到的 RequiresAuthentication() 对整个模块进行身份验证检查。每条路线有什么方法可以做到这一点吗?
【问题讨论】:
标签: authentication routes nancy
我遇到了同样的问题,我是这样解决的。
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"};
});
});
我现在可以在模块级别使用 this.RequiresAuthentication() 并运行我的单元测试。
【讨论】:
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
}
}
【讨论】:
我遇到了同样的问题。然而事实证明RequiresAuthentication 在模块级别和路由级别都有效。为了演示,这里是我当前项目的一些代码(为简洁起见,并非所有路线都显示)。
public class RegisterModule : _BaseModule
{
public RegisterModule() : base("/register")
{
Get["/basic-details"] = _ => View["RegisterBasicDetailsView", Model];
Get["/select"] = _ =>
{
this.RequiresAuthentication();
return View["RegisterSelectView", Model];
};
}
}
当然,这样做的唯一问题是模块中所有受保护的路由都需要调用RequiresAuthentication。对于上面的模块,我还有另外 5 条路由(未显示),所有这些路由都需要保护,因此需要对 RequiresAuthentication 进行 6 次调用,而不是在模块级别调用 1 次。另一种方法是将不受保护的路由拉到另一个模块中,但我的判断是模块的扩散比额外的 RequiresAuthentication 调用更糟糕。
【讨论】: