简体   繁体   English

TestServer CreateClient和HttpClientHandler - howto?

[英]TestServer CreateClient and HttpClientHandler - howto?

I'm using the AspNetCore TestServer and trying to connect to an API service configured for NTLM Authentication. 我正在使用AspNetCore TestServer并尝试连接到为NTLM身份验证配置的API服务。 The service I'm connecting to needs to access the System.Security.Claims.ClaimsPrincipal.Identity. 我要连接的服务需要访问System.Security.Claims.ClaimsPrincipal.Identity。

From my Console application I can initialise he HTTPClient as follows and it works 从我的控制台应用程序,我可以如下初始化他的HTTPClient,它的工作原理

HttpClientHandler handler = new HttpClientHandler()
{
    UseDefaultCredentials = true,
    PreAuthenticate = true
};

HttpClient client = new HttpClient(handler);

However, the TestServer CreateClient method does not accept a HttpClientHandler. 但是,TestServer CreateClient方法不接受HttpClientHandler。 So how do I configure to use UseDefaultCredentials? 那么如何配置使用UseDefaultCredentials?

An option is to create an overloaded constructor on your HttpClientHandler and wrap the TestServer's HttpClientHandler. 一个选项是在HttpClientHandler上创建一个重载的构造函数并包装TestServer的HttpClientHandler。 There, from the SendAsync method you just need to Invoke the method SendAsync of he TestServer's HttpClientHandler like this 在那里,从SendAsync方法你只需要调用他的TestServer的HttpClientHandler的方法SendAsync,就像这样

if (_wrappedMessageHandler != null)
{
    var method = typeof(HttpMessageHandler).GetMethod("SendAsync", BindingFlags.Instance | BindingFlags.NonPublic);
    var result = method.Invoke(_wrappedMessageHandler, new object[] { request, cancellationToken });
    return await (Task<HttpResponseMessage>)result;
}
else
{
    var response = await base.SendAsync(request, cancellationToken);
    return response;

}

You can't do windows auth with the test server. 您无法使用测试服务器执行Windows身份验证。 A related feature was added for an upcoming release. 为即将发布的版本添加了相关功能。 https://github.com/aspnet/Hosting/pull/1248 . https://github.com/aspnet/Hosting/pull/1248 See the linked issues and PRs for workarounds via middleware. 通过中间件查看链接的问题和PR以获取变通方法。

To resolve this issue I inject the user throught a middleware in my test: 为了解决这个问题,我在测试中注入了一个中间件用户:

public class FakeIdentity : IIdentity
{
    public string AuthenticationType => "fake";

    public bool IsAuthenticated => true;

    public string Name => "fake";
}

public class TestUtils
{
    public static TestServer CreateTestServer()
    {
        Startup startup = null;
        var webHostBuilder = new WebHostBuilder()
            .ConfigureServices((context, services) =>
            {
                startup = new Startup(context.Configuration);
                startup.ConfigureServices(services);
            })
            .Configure(builder =>
            {
            var services = builder.ApplicationServices;
            using (var scope = services.CreateScope())
            {
                builder.Use(async (context, next) =>
                {
                    context.User = new ClaimsPrincipal(new ClaimsIdentity(new FakeIdentity(), new List<Claim>
                    {
                                // a list of claims the application need
                            }));
                    await next();
                });
                startup.Configure(builder, services.GetRequiredService<IHostingEnvironment>());
            });

        var testServer = new TestServer(webHostBuilder);

        return testServer;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM