There is a new way for Microsoft.Graph 4+ in this article. Yet I had to achieve this using mix of two ways due to our azure adfs only auth requests are coming from browsers. Hope this will help full to others.
private GraphServiceClient GetGraphClient()
{
string[] scopes = new string[] { "User.Read", "User.ReadBasic.All", "Mail.Read", "Mail.ReadWrite", "Mail.Send" };
var msalFactory = new MsalHttpClientFactoryOwn(_configuration);
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create("")
.WithTenantId("")
.WithHttpClientFactory(msalFactory)
.Build();
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);
HttpClient httpClient = GraphClientFactory.Create(authProvider, "v1.0", "Global", msalFactory.GetWebProxy());
var graphClient = new GraphServiceClient(httpClient);
return graphClient;
}
public class MsalHttpClientFactoryOwn : IMsalHttpClientFactory
{
private readonly IConfiguration configuration;
public ProxiedHttpClientFactory(IConfiguration configuration)
{
this.configuration = configuration;
}
public HttpClient GetHttpClient()
{
var proxyHttpClientHandler = new HttpClientHandler()
{
UseProxy = true,
UseDefaultCredentials = false,
Credentials = GetNetworkCredentials(),
Proxy = GetWebProxy()
};
var httpClient = new HttpClient(proxyHttpClientHandler);
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
httpClient.Timeout = TimeSpan.FromMinutes(30);
return httpClient;
}
public WebProxy GetWebProxy()
{
var proxy = new WebProxy
{
Address = new Uri("proxy address"),
BypassProxyOnLocal = false,
UseDefaultCredentials = false,
Credentials = GetNetworkCredentials()
};
return proxy;
}
private NetworkCredential GetNetworkCredentials()
{
var networkCreds = new NetworkCredential(u, p);
return networkCreds;
}
}