2016-11-25 2 views
0

안녕하세요, 저는 Owin 인프라를 사용하여 간단한 http 프록시 서비스를 구현하려고합니다. 이 프록시는 Windows 인증을 통해 사용자를 인증하고 엔터프라이즈 AD에서 사용자의 속성을 가져 와서이 정보를 쿠키 값으로 원래 요청에 추가 한 다음 요청을 인터넷의 응용 프로그램으로 리디렉션해야합니다 (외부 응용 프로그램이라고 함)..Net HttpClient로 '요청 별'쿠키 설정

HttpClient를 사용하여 외부 응용 프로그램에 요청을 보내고 있습니다.

그러나 HttpClient는이 시나리오에 적합하지 않습니다. 그것을 사용하여 쿠키를 보내는 유일한 방법은 쿠키를 CookieContainer에 넣고이 CookieContainer를 HttpClientHandler의 속성으로 설정하는 것입니다. 단일 사용자 일 때도 괜찮지 만 프록시 서비스의 경우 다른 사용자의 쿠키 값이 서로 섞여서 덮어 쓰게됩니다.

요청마다 쿠키 또는 CookieContainer를 설정할 수있는 방법이 있습니까? 아니면 요청을 리디렉션하는 더 좋은 방법이 있을까요?

P. 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) 
    } 
} 
+0

제안 해 주셔서 감사합니다. 실제로 트래픽이 많을 것으로 예상됩니다. –

답변

0

찾을 솔루션 : enter link description here 트릭 명시 적으로 거짓에 HttpClientHandler의 UseCookie 플래그를 설정입니다.

var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Automatic, UseCookie = false };