2012-08-29 44 views
3

從我在源代碼中看到的RequiresAuthentication()對整個模塊進行認證檢查。有沒有什麼辦法可以按照路線做到這一點?NancyFx每個路由的認證

回答

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 

    } 
} 
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調用更差。

+0

我沒有嘗試從路由中調用RequiresAuthentication,因爲在查看源代碼後似乎沒有工作。我創建了一個新的擴展方法,對context.CurrentUser執行相同的檢查,但返回bool。 – Emilian

+0

你可以爲你的擴展方法提供代碼嗎? – biofractal

+0

我已經發布了下面的代碼,你可以像this.WithAuthentication(()=> {/ *需要認證用戶* /}的代碼)使用它; – Emilian

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()並運行我的單元測試。