【问题标题】:NancyFx Authentication per Route每个路由的 NancyFx 身份验证
【发布时间】:2012-08-24 11:53:39
【问题描述】:

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

【问题讨论】:

    标签: authentication routes nancy


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

    【讨论】:

      【解决方案2】:
      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
      
          }
      }
      

      【讨论】:

        【解决方案3】:

        我遇到了同样的问题。然而事实证明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 调用更糟糕。

        【讨论】:

        • 我没有尝试从路由调用 RequiresAuthentication ,因为在查看源代码后似乎没有工作。我创建了一个新的扩展方法,它对 context.CurrentUser 进行相同的检查,但返回 bool。
        • 我把下面的代码贴出来了,你可以这样使用。WithAuthentication(() => { /* 需要认证用户的代码 */ });
        猜你喜欢
        • 2015-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多