El cliente Graph Microsoft está diseñado para facilitar la realización de llamadas a Microsoft Graph. Puede usar una sola instancia de cliente durante la vigencia de la aplicación. Para obtener información sobre cómo agregar e instalar el paquete de cliente de Microsoft Graph en el proyecto, vea Install the SDK.
Los ejemplos de código siguientes muestran cómo crear una instancia de un cliente de Microsoft Graph con un proveedor de autenticación en los idiomas admitidos. El proveedor de autenticación controlará la adquisición de tokens de acceso para la aplicación. Hay muchos proveedores de autenticación diferentes disponibles para cada idioma y plataforma. Los distintos proveedores de autenticación admiten distintos escenarios de cliente. Para obtener más información sobre qué proveedor y opciones son adecuadas para su escenario, vea Choose an Authentication Provider.
var scopes = new[] { "User.Read" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";
// Value from app registration
var clientId = "YOUR_CLIENT_ID";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// Callback function that receives the user prompt
// Prompt contains the generated device code that use must
// enter during the auth process in the browser
Func<DeviceCodeInfo, CancellationToken, Task> callback = (code, cancellation) => {
Console.WriteLine(code.Message);
return Task.FromResult(0);
};
// https://docs.microsoft.com/dotnet/api/azure.identity.devicecodecredential
var deviceCodeCredential = new DeviceCodeCredential(
callback, tenantId, clientId, options);
var graphClient = new GraphServiceClient(deviceCodeCredential, scopes);
const {
Client
} = require("@microsoft/microsoft-graph-client");
const {
TokenCredentialAuthenticationProvider
} = require("@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials");
const {
DeviceCodeCredential
} = require("@azure/identity");
const credential = new DeviceCodeCredential(tenantId, clientId, clientSecret);
const authProvider = new TokenCredentialAuthenticationProvider(credential, {
scopes: [scopes]
});
const client = Client.initWithMiddleware({
debugLogging: true,
authProvider
// Use the authProvider object to create the class.
});
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();
Importante
Microsoft Graph SDK for Go está actualmente en versión preliminar. No se admite el uso de este SDK en producción.