Skip to content
This repository has been archived by the owner on Jun 30, 2023. It is now read-only.

with proxy

Bogdan Gavril edited this page Jan 22, 2019 · 14 revisions

Provide your own HttpClient

ADAL communicates with AAD using HttpClient. There are many scenarios where you need to customise this HttpClient, the most common scenario being having to use a proxy server.

Starting with ADAL 4.5.0, a new constructor for AuthenticationContext that takes in an HttpClient has been added.

HttpClient httpClient = CreateCustomHttpClient(); // set a proxy, add headers etc. 

AuthenticationContext authenticationContext = new AuthenticationContext(
      authority: "https://login.microsoftonline.com/common",
      validateAuthority: true, 
      // on .Net and .Net core define your own cache persistence (omitted here for brevity)
      tokenCache: TokenCache.DefaultShared, 
      httpClient: httpClient);

// Now call into ADAL using the standard pattern - AcquireTokenSilent then AcquireToken

This is how to specify a proxy. For more details see the MSDN docs.

var proxy = new WebProxy()
{
    Address = new Uri("localhost:8080"),
    BypassOnLocal = false,
    UseDefaultCredentials = false,

    // *** These creds are given to the proxy server, not the web server ***
    Credentials = new NetworkCredential(
        userName: "proxyUserName",
        password: "proxyPassword");
};

// Now create a client handler which uses that proxy
var httpClientHandler = new HttpClientHandler()
{
    Proxy = proxy,
};

// Finally, create the HTTP client object
var client = new HttpClient(handler: httpClientHandler, disposeHandler: true);

For reference, this is how ADAL configures its HttpClient if you don't specify one:

var httpClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true })
{
    MaxResponseContentBufferSize = 1 * 1024 * 1024 // 1 MB
};

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Older versions

Previous to ADAL 4.5.0 ADAL.NET does not propose any API to set a proxy, however you can use the system level API: the HttpClients used by ADAL.NET are able to use it.

using System.Net;
...
{
 // Set the proxy
 IWebProxy proxy = new WebProxy("http://proxyserver:80", true);
 // This does not work on .Net Core https://github.com/dotnet/corefx/issues/7037
 WebRequest.DefaultWebProxy = proxy; 

 // Use ADAL.NET
}
Clone this wiki locally