The Microsoft Graph SDK client configures a default set of middleware that allows the SDK to communicate with the Microsoft Graph endpoints. This customizable default set allows you to change the client's behavior. For example, you can insert customized logging or a test handler to simulate specific scenarios. You can add and remove middleware components. It's important to note that the order in which middleware components run is significant.
// tokenCredential is one of the credential classes from Azure.Identity
// scopes is an array of permission scope strings
var authProvider = new AzureIdentityAuthenticationProvider(tokenCredential, scopes: scopes);
var handlers = GraphClientFactory.CreateDefaultHandlers();
// Remove a default handler
// Microsoft.Kiota.Http.HttpClientLibrary.Middleware.CompressionHandler
var compressionHandler =
handlers.Where(h => h is CompressionHandler).FirstOrDefault();
handlers.Remove(compressionHandler);
// Add a new one
// ChaosHandler simulates random server failures
// Microsoft.Kiota.Http.HttpClientLibrary.Middleware.ChaosHandler
handlers.Add(new ChaosHandler());
var httpClient = GraphClientFactory.Create(handlers);
var customGraphClient = new GraphServiceClient(httpClient, authProvider);
// tokenCredential is one of the credential classes from azidentity
// scopes is an array of permission scope strings
authProvider, _ := authentication.NewAzureIdentityAuthenticationProviderWithScopes(credential, scopes)
// Get default middleware from SDK
defaultClientOptions := graph.GetDefaultClientOptions()
defaultMiddleWare := graphcore.GetDefaultMiddlewaresWithOptions(&defaultClientOptions)
// Add chaos handler to default middleware
chaosHandler := khttp.NewChaosHandler()
allMiddleware := append(defaultMiddleWare, chaosHandler)
// Create an HTTP client with the middleware
httpClient := khttp.GetDefaultClient(allMiddleware...)
// Create the adapter
// Passing nil values causes the adapter to use default implementations
adapter, _ :=
graph.NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient(
authProvider, nil, nil, httpClient)
graphClient := graph.NewGraphServiceClient(adapter)
// tokenCredential is one of the credential classes from azure-identity
// scopes is a list of permission scope strings
final TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(
scopes, credential);
final ChaosHttpHandler chaosHandler = new ChaosHttpHandler();
final OkHttpClient httpClient = HttpClients.createDefault(authProvider)
.newBuilder().addInterceptor(chaosHandler).build();
if (null == httpClient) {
throw new Exception("Could not create HTTP client.");
}
final GraphServiceClient<Request> graphClient = GraphServiceClient.builder()
.httpClient(httpClient).buildClient();
We currently use Guzzle as our HTTP client. You can pass your custom-configured Guzzle client using:
<?php
use Microsoft\Graph\Core\GraphClientFactory;
use Microsoft\Graph\GraphRequestAdapter;
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Graph\Core\Authentication\GraphPhpLeagueAuthenticationProvider;
$tokenRequestContext = new ClientCredentialContext(
'tenantId',
'clientId',
'clientSecret'
);
$authProvider = new GraphPhpLeagueAuthenticationProvider($tokenRequestContext);
// Get default middleware stack from SDK
$handlerStack = GraphClientFactory::getDefaultHandlerStack();
// Add a custom handler or extra handlers not added by default
// Add Chaos handler to simulate random server failure responses
$handlerStack->push(KiotaMiddleware::chaos());
$httpClient = GraphClientFactory::createWithMiddleware($handlerStack);
$requestAdapter = new GraphRequestAdapter($authProvider, $httpClient);
$graphServiceClient = new GraphServiceClient($requestAdapter);
# Create an authentication provider
# credential is one of the credential classes from azure.identity
# scopes is an array of permission scope strings
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
# Get default middleware
# msgraph_core.GraphClientFactory
middleware = GraphClientFactory.get_default_middleware(options=None)
# Add custom middleware
# Implement a custom middleware by extending the BaseMiddleware class
# https://github.com/microsoft/kiota-http-go/blob/main/kiota_http/middleware/middleware.py
middleware.append(CustomMiddleware())
# Create an HTTP client with the middleware
http_client = GraphClientFactory.create_with_custom_middleware(middleware)
# Create a request adapter with the HTTP client
adapter = GraphRequestAdapter(auth_provider, http_client)
# Create the Graph client
graph_client = GraphServiceClient(request_adapter=adapter)
// credential is one of the credential classes from @azure/identity
// scopes is an array of permission scope strings
const authProvider = new TokenCredentialAuthenticationProvider(credential, {
scopes: scopes,
});
// Create an authentication handler (from @microsoft/microsoft-graph-client)
const authHandler = new AuthenticationHandler(authProvider);
// Create a chaos handler (from @microsoft/microsoft-graph-client)
const chaosHandler = new ChaosHandler();
// Create a standard HTTP handler (from @microsoft/microsoft-graph-client)
const httpHandler = new HTTPMessageHandler();
// Use setNext to chain handlers together
// auth -> chaos -> http
authHandler.setNext(chaosHandler);
chaosHandler.setNext(httpHandler);
// Pass the first middleware in the chain in the middleWare property
const graphClient = Client.initWithMiddleware({
middleware: authHandler,
});
Configuring the HTTP proxy for the client
Some environments require client applications to use an HTTP proxy before accessing the public internet. This section shows how to configure the proxy for the Microsoft Graph SDKs.
// URI to proxy
var proxyAddress = "http://localhost:8888";
var authProvider = new AzureIdentityAuthenticationProvider(tokenCredential, scopes);
// This example works with Microsoft.Graph 5+
var httpClient = GraphClientFactory.Create(proxy: new WebProxy(new Uri(proxyAddress)));
var graphClient = new GraphServiceClient(httpClient, authProvider);
// tokenCredential is one of the credential classes from azidentity
// scopes is an array of permission scope strings
authProvider, _ := authentication.NewAzureIdentityAuthenticationProviderWithScopes(credential, scopes)
// Get default middleware from SDK
defaultClientOptions := graph.GetDefaultClientOptions()
defaultMiddleWare := graphcore.GetDefaultMiddlewaresWithOptions(&defaultClientOptions)
// Create an HTTP client with the middleware
httpClient, _ := khttp.GetClientWithProxySettings("http://proxy-url", defaultMiddleWare...)
// For authenticated proxy, use
// khttp.GetClientWithAuthenticatedProxySettings(
// "http://proxy-url", "user", "password", defaultMiddleWare...)
// Create the adapter
// Passing nil values causes the adapter to use default implementations
adapter, _ :=
graph.NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient(
authProvider, nil, nil, httpClient)
graphClient := graph.NewGraphServiceClient(adapter)
// tokenCredential is one of the credential classes from azure-identity
// scopes is a list of permission scope strings
final TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(
scopes, credential);
final String proxyHost = "localhost";
final int proxyPort = 8888;
final InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost,
proxyPort);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
// This object is only needed if the proxy requires authentication
final Authenticator proxyAuthenticator = new Authenticator() {
@Override
public Request authenticate(Route route, Response response)
throws IOException {
String credential = Credentials.basic("username", "password");
return response.request().newBuilder()
.header("Proxy-Authorization", credential).build();
}
};
// Omit proxyAuthenticator if no authentication required
final OkHttpClient httpClient = HttpClients.createDefault(authProvider)
.newBuilder().proxy(proxy).proxyAuthenticator(proxyAuthenticator).build();
if (null == httpClient) {
throw new Exception("Could not create HTTP client.");
}
final GraphServiceClient<Request> graphClient = GraphServiceClient.builder()
.httpClient(httpClient).buildClient();
<?php
use Microsoft\Graph\Core\GraphClientFactory;
use Microsoft\Graph\GraphRequestAdapter;
// Configure proxy URLs on the Guzzle client
$guzzleConfig = [
'proxy' => [
'http' => 'http://proxy-url', // Use this proxy with "http"
'https' => 'http://proxy-url', // Use this proxy with "https"
]
];
$httpClient = GraphClientFactory::createWithConfig($guzzleConfig);
$requestAdapter = new GraphRequestAdapter($authProvider, $httpClient);
$graphServiceClient = GraphServiceClient::createWithRequestAdapter($requestAdapter);
# Create an authentication provider
# credential is one of the credential classes from azure.identity
# scopes is an array of permission scope strings
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
# Proxy URLs
proxies = {
'http://': 'http://proxy-url',
'https://': 'http://proxy-url',
}
# Create a custom HTTP client with the proxies
# httpx.AsyncClient
http_client = AsyncClient(proxies=proxies) # type: ignore
# Apply the default Graph middleware to the HTTP client
http_client = GraphClientFactory.create_with_default_middleware(client=http_client)
# Create a request adapter with the HTTP client
adapter = GraphRequestAdapter(auth_provider, http_client)
# Create the Graph client
graph_client = GraphServiceClient(request_adapter=adapter)
// credential is one of the credential classes from @azure/identity
// scopes is an array of permission scope strings
const authProvider = new TokenCredentialAuthenticationProvider(credential, {
scopes: scopes,
});
// Create a new HTTPS proxy agent (from https-proxy-agent)
const proxyAgent = new HttpsProxyAgent('http://localhost:8888');
// Create a client with the proxy
const graphClient = Client.initWithMiddleware({
authProvider: authProvider,
fetchOptions: {
agent: proxyAgent,
},
});