18

我刚刚开始将 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 测试服务器进行身份验证或至少绕过身份验证?

4

1 回答 1

20

我已经能够以一种我确信是次优的方式来解决这个问题,但是在我遇到更好的解决方案或者你们中的一个人告诉我一个更好的方法来做到这一点之前,我必须这样做:) 我'已经做到了如下:

  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;
    }
    
  2. 实现了一个仅用于集成测试的授权过滤器:

    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)
        {
    
        }
    }
    
  3. 在我的集成测试的设置代码中,我注入了测试授权过滤器:

    Startup.CreateAuthFilter = () => new TestAuthFilter();
    var TestServer = TestServer.Create<Startup>();
    
  4. 在特定测试中需要时,我将 TestUserId 设置为已知值,而其他测试似乎只是工作,因为存在 Auth 过滤器:

    TestAuthFilter.TestUserId = testUser.UserId;
    

我在这里分享这个,以防它帮助其他人,但请有人告诉我更好的方法!至少我确信有更好的方法来注入我的测试过滤器而不在启动中包含代码......我只是没有想到它。

于 2013-11-12T03:11:15.427 回答