我刚开始将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."}
如何使用内存中的OWIN测试服务器进行身份验证或至少绕过身份验证?
我已经能够以某种肯定最佳的方式来解决此问题,但是必须等到遇到更好的解决方案,或者你们中的一个很好的人告诉我一种更好的方法时才可以这样做:)我已完成,如下所示:
在我的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;
}
实现了仅在集成测试中使用的授权过滤器:
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)
{
}
}
在用于集成测试的设置代码中,注入测试授权过滤器:
Startup.CreateAuthFilter = () => new TestAuthFilter();
var TestServer = TestServer.Create<Startup>();
在特定测试中需要时,我将TestUserId设置为已知值,并且其他测试似乎也可以正常工作,因为存在Auth过滤器:
TestAuthFilter.TestUserId = testUser.UserId;
我在这里分享这是为了帮助别人,但是请有人告诉我更好的方法!至少我敢肯定,有一种更好的方法可以在不将代码包含在启动中的情况下注入测试过滤器……我只是没有想到这一点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句