嗨,我正在尝试使用Owin基础结构实现简单的http代理服务。此代理必须使用Windows身份验证对用户进行身份验证,从企业AD中获取用户的属性,将此信息作为cookie值添加到原始请求中,然后将请求重定向到Internet上的应用程序(称为外部应用程序)。
我正在使用HttpClient将请求发送到外部应用程序。
但是HttpClient不适用于此方案。似乎唯一允许使用它发送cookie的方法是将其放入CookieContainer并将此CookieContainer设置为HttpClientHandler的属性。如果您只有一个用户,则可以,但是在代理服务的情况下,来自不同用户的Cookie值将相互混合并覆盖。
有什么方法可以根据请求设置cookie或CookieContainer吗?或者,也许有更好的方法来重定向请求?
PS这是一些代码:
http处理程序的初始化:
private void RegisterRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Proxy",
routeTemplate: "{*path}",
handler: HttpClientFactory.CreatePipeline
(
innerHandler: new HttpClientHandler(),
handlers: new DelegatingHandler[]
{
new ProxyHandler()
}
),
defaults: new { path = RouteParameter.Optional },
constraints: null);
}
ProxyHandler内部类ProxyHandler:DelegatingHandler {私有只读HttpClient _client;
public ProxyHandler()
{
var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Automatic};
_client = new HttpClient(handler);
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var forwardUri = new UriBuilder(request.RequestUri);
forwardUri.Host = "localhost";
forwardUri.Port = 23016;
forwardUri.Scheme = Uri.UriSchemeHttp;
request.RequestUri = forwardUri.Uri;
request.Headers.Host = forwardUri.Host;
//Explicitly null it to avoid protocol violation
if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Trace)
request.Content = null;
try
{
var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
//Explicitly null it to avoid protocol violation
if (request.Method == HttpMethod.Head)
response.Content = null;
return response;
}
catch (Exception ex)
{
var response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
string message = ex.Message;
if (ex.InnerException != null)
message += ':' + ex.InnerException.Message;
response.Content = new StringContent(message);
Trace.TraceError("Error:{0}", message);
return response;
}
}
private void SetCookies(HttpRequestMessage request)
{
var container = new CookieContainer();
var authCookieValue = "2EF91D8FD9EDC594F2DB82";
var authCookie = new Cookie("cookieByProxy", authCookieValue);
var targetUri = new Uri("http://localhost:23016/");
container.Add(targetUri, authCookie);
var cookieHeader = container.GetCookieHeader(targetUri);
if (!string.IsNullOrEmpty(cookieHeader))
request.Headers.TryAddWithoutValidation("Cookie", cookieHeader);//Overwriting cookie header with custom values. However cookie values are ignored by HttpClient (both old and new)
}
}
在此处找到解决方案:在此处输入链接描述技巧是将HttpClientHandler的UseCookie标志显式设置为false。
var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Automatic, UseCookie = false };
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句