O cliente do Microsoft Graph foi projetado para facilitar as chamadas para o Microsoft Graph.The Microsoft Graph client is designed to make it simple to make calls to Microsoft Graph.Você pode usar uma única instância do cliente durante o tempo de vida do aplicativo.You can use a single client instance for the lifetime of the application.Para obter informações sobre como adicionar e instalar o pacote cliente do Microsoft Graph em seu projeto, consulte Install the SDK.For information about how to add and install the Microsoft Graph client package into your project, see Install the SDK.
Os exemplos de código a seguir mostram como criar uma instância de um cliente do Microsoft Graph com um provedor de autenticação nos idiomas suportados.The following code examples show how to create an instance of a Microsoft Graph client with an authentication provider in the supported languages.O provedor de autenticação tratará da aquisição de tokens de acesso para o aplicativo.The authentication provider will handle acquiring access tokens for the application.Muitos provedores de autenticação diferentes estão disponíveis para cada idioma e plataforma.Many different authentication providers are available for each language and platform.Os diferentes provedores de aplicativos suportam diferentes cenários de cliente.The different application providers support different client scenarios.Para obter detalhes sobre quais provedores e opções são apropriados para seu cenário, consulte Choose an Authentication Provider.For details about which provider and options are appropriate for your scenario, see Choose an Authentication Provider.
// Build a client application.
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create("INSERT-CLIENT-APP-ID")
.Build();
// Create an authentication provider by passing in a client application and graph scopes.
DeviceCodeProvider authProvider = new DeviceCodeProvider(publicClientApplication, graphScopes);
// Create a new instance of GraphServiceClient with the authentication provider.
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
const clientId = "INSERT-CLIENT-APP-ID"; // Client Id of the registered application
const callback = (errorDesc, token, error, tokenType) => {};
// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
const options = {
redirectUri: "Your redirect URI",
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#initialization-of-msal
const userAgentApplication = new UserAgentApplication(clientId, undefined, callback, options);
const authProvider = new MSALAuthenticationProvider(userAgentApplication, graphScopes );
final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.tenantId(TENANT_GUID)
.build();
final TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(SCOPES, clientSecretCredential);
final GraphServiceClient graphClient = GraphServiceClient
.builder()
.authenticationProvider(tokenCredAuthProvider)
.buildClient();
final InteractiveBrowserCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder()
.clientId(CLIENT_ID)
.redirectUrl("http://localhost:8765")
.build();
final TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(SCOPES, interactiveBrowserCredential);
GraphServiceClient graphClient = GraphServiceClient
.builder()
.authenticationProvider(tokenCredAuthProvider)
.buildClient();
// Create the authenticationProvider.
NSError *error = nil;
MSALPublicClientApplication *publicClientApplication = [[MSALPublicClientApplication alloc] initWithClientId:@"INSERT-CLIENT-APP-ID"
error:&error];
MSALAuthenticationProviderOptions *authProviderOptions= [[MSALAuthenticationProviderOptions alloc] initWithScopes:<array-of-scopes-for-which-you-need-access-token>];
MSALAuthenticationProvider *authenticationProvider = [[MSALAuthenticationProvider alloc] initWithPublicClientApplication:publicClientApplication
andOptions:authProviderOptions];
// Create the client with the authenticationProvider and create a request to the /me resource.
MSHTTPClient *httpClient = [MSClientFactory createHTTPClientWithAuthenticationProvider:authenticationProvider];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[MSGraphBaseURL stringByAppendingString:@"/me"]]];
// Create the task to send the request and handle the response.
MSURLSessionDataTask *meDataTask = [httpClient dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Do something
}];
[meDataTask execute];
// PHP client currently doesn't have an authentication provider. You will need to handle
// getting an access token. The following example demonstrates the client credential
// OAuth flow and assumes that an administrator has consented to the application.
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
$accessToken = $token->access_token;
// Create a new Graph client.
$graph = new Graph();
$graph->setAccessToken($accessToken);
// Make a call to /me Graph resource.
$user = $graph->createRequest("GET", "/me")
->setReturnType(Model\User::class)
->execute();