Asp.net

使用 Microsoft.Owin.Testing.TestServer 進行記憶體集成測試的身份驗證

  • November 11, 2013

我剛剛開始將 OWIN\Katana 用於 Web api 項目。它使用 Windows 身份驗證。這似乎有效,但我的大多數集成測試都失敗了。他們以前只是使用 In-Memory HttpServer,但我已改為使用Microsoft.Owin.Testing.TestServer. 我在我的測試設置中替換了這樣的東西:

       var config = new HttpConfiguration { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };
       config.EnableQuerySupport();
       Server = new HttpServer(config);
       MyConfigClass.Configure(config);
       WebApiConfig.Register(config);

用一個更簡單的:

TestServer = TestServer.Create<Startup>();

但是以前我可以將以下內容用於記憶體伺服器的“假”身份驗證:

Thread.CurrentPrincipal = new ClientRolePrincipal(new HttpListenerBasicIdentity(Username, Password));

現在這行不通了。對於所有請求,我得到以下資訊:

System.Exception : {"Message":"Authorization has been denied for this request."}

如何使用 In-Memory OWIN 測試伺服器進行身份驗證或至少繞過身份驗證?

我已經能夠以一種我確信是次優的方式來解決這個問題,但是在我遇到更好的解決方案或者你們中的一個人告訴我一個更好的方法來做到這一點之前,我必須這樣做:) 我’已經做到瞭如下:

  1. 在我的 Startup 類中,我添加了一個 CreateAuthFilter 掛鉤,稍後我們將看到它僅用於集成測試:
// Sample Startup class
public class Startup
{
   public void Configuration(IAppBuilder app)
   {
       var config = new HttpConfiguration();

       // Use CreateFilter Method to create Authorisation Filter -  if not null add it
       var authFilter = CreateAuthFilter();
       if(authFilter != null)
           config.Filters.Add(authFilter);

       // Other configuration and middleware...
   }

   public static Func<IFilter> CreateAuthFilter = () => null;
}
  1. 實現了一個僅用於集成測試的授權過濾器:
public class TestAuthFilter : IAuthenticationFilter
{
   static TestAuthFilter()
   {
       TestUserId = "TestDomain\\TestUser";
   }

   public bool AllowMultiple { get; private set; }

   public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
   {
       context.Principal = new ClientRolePrincipal(new HttpListenerBasicIdentity(TestUserId, "password")); ;
   }

   public static string TestUserId { get; set; }

   public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
   {

   }
}
  1. 在我的集成測試的設置程式碼中,我注入了測試授權過濾器:
Startup.CreateAuthFilter = () => new TestAuthFilter();
var TestServer = TestServer.Create<Startup>();
  1. 在特定測試中需要時,我將 TestUserId 設置為已知值,而其他測試似乎只是工作,因為存在 Auth 過濾器:
TestAuthFilter.TestUserId = testUser.UserId;

我在這里分享這個,以防它幫助其他人,但請有人告訴我更好的方法!至少我確信有更好的方法來注入我的測試過濾器而不在啟動中包含程式碼……我只是沒有想到它。

引用自:https://stackoverflow.com/questions/19897705