Search code examples
c#microsoft-graph-apihttp-proxy

Proxy Configuration for C# GraphSdk


I need to relay the HTTP-Requests made by the C# Graph-Sdk over a proxy.

In the documentation I could not find any information about proxy settings. The only workaraound I currently found is to change the global proxy settings:

System.Net.GlobalProxySelection.Select = proxy;
or
System.Net.WebRequest.DefaultWebProxy = proxy;

Sadly in my situation this is not possible without moving all graph related features into a separate process (as the rest of the main-process needs to run without proxy).

So my Question is:

  • Is there any official support for Proxy Settings in the sdk?

  • And is support for Proxy Settings planned for future sdk-versions?


Solution

  • You can set the proxy when you instantiate your GraphServiceClient.

    Update 6/9/2021

    There is now a better way by using the GraphClientFactory.

    HttpClient httpClient = GraphClientFactory.Create(GetClientCredentialProvider(), "v1.0", "Global", new WebProxy(""));
    var graphServiceClient = new(httpClient);
    

    Old answer

    System.Net.Http.HttpClientHandler httpClientHandler = new System.Net.Http.HttpClientHandler()
    {
        AllowAutoRedirect = false,
        Proxy = new WebProxy() // TODO: Set your proxy settings. 
    };
    
    HttpProvider httpProvider = new HttpProvider(httpClientHandler, true);
    
    GraphServiceClient client = new GraphServiceClient("https://graph.microsoft.com/v1.0",
            new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    var token = await goGetSomeTokenNow();
                    requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", token);
    
                }), httpProvider);