每个路由的NancyFx身份验证

时间:2012-08-29 19:35:44

标签: authentication routes nancy

从我在源代码中看到的,RequiresAuthentication()对整个模块进行身份验证检查。每条路线有没有办法做到这一点?

3 个答案:

答案 0 :(得分:5)

我遇到了同样的问题。然而事实证明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而不是一次。另一种方法是将未受保护的路由引入另一个模块,但我的判断是模块的扩散比额外的RequiresAuthentication调用更糟糕。

答案 1 :(得分:1)

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

    }
}

答案 2 :(得分:1)

我遇到了同样的问题,这就是我解决它的方法。

        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()并运行我的单元测试。

相关问题