El cliente de Microsoft Graph está diseñado para facilitar la realización de llamadas a Microsoft Graph. Puede usar una única instancia de cliente durante la duración de la aplicación. Para obtener información sobre cómo agregar e instalar el paquete de cliente de Microsoft Graph en el proyecto, consulte Instalación del SDK.
En los ejemplos de código siguientes se muestra 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 controla la adquisición de tokens de acceso para la aplicación.
Hay muchos proveedores de autenticación diferentes disponibles para cada lenguaje y plataforma. Los distintos proveedores de autenticación admiten diferentes escenarios de cliente. Para obtener más información sobre qué proveedor y opciones son adecuadas para su escenario, consulte Elegir un proveedor de autenticación.
El identificador de cliente es el identificador de registro de la aplicación que se genera al registrar la aplicación en el Azure Portal.
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 DeviceCodeCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
ClientId = clientId,
TenantId = tenantId,
// Callback function that receives the user prompt
// Prompt contains the generated device code that user must
// enter during the auth process in the browser
DeviceCodeCallback = (code, cancellation) =>
{
Console.WriteLine(code.Message);
return Task.FromResult(0);
},
};
// https://learn.microsoft.com/dotnet/api/azure.identity.devicecodecredential
var deviceCodeCredential = new DeviceCodeCredential(options);
var graphClient = new GraphServiceClient(deviceCodeCredential, scopes);
Incluya using
instrucciones para Azure.Identity
y Microsoft.Graph
para ejecutar este código.
cred, _ := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
TenantID: "TENANT_ID",
ClientID: "CLIENT_ID",
UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
fmt.Println(message.Message)
return nil
},
})
graphClient, _ := graph.NewGraphServiceClientWithCredentials(
cred, []string{"User.Read"})
Incluya "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
y graph "github.com/microsoftgraph/msgraph-sdk-go"
en el bloque de importación para ejecutar este código.
final String clientId = "YOUR_CLIENT_ID";
final String tenantId = "YOUR_TENANT_ID"; // or "common" for multi-tenant apps
final String[] scopes = new String[] {"User.Read"};
final DeviceCodeCredential credential = new DeviceCodeCredentialBuilder()
.clientId(clientId).tenantId(tenantId).challengeConsumer(challenge -> {
// Display challenge to the user
System.out.println(challenge.getMessage());
}).build();
if (null == scopes || null == credential) {
throw new Exception("Unexpected error");
}
final GraphServiceClient graphClient = new GraphServiceClient(credential, scopes);
Incluya import
instrucciones para com.azure.identity.DeviceCodeCredential
, com.azure.identity.DeviceCodeCredentialBuilder
y com.microsoft.graph.serviceclient.GraphServiceClient
para ejecutar este código.
$scopes = ['User.Read'];
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
$tenantId = 'common';
// Values from app registration
$clientId = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET';
$redirectUri = 'YOUR_REDIRECT_URI';
// For authorization code flow, the user signs into the Microsoft
// identity platform, and the browser is redirected back to your app
// with an authorization code in the query parameters
$authorizationCode = 'AUTH_CODE_FROM_REDIRECT';
// Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext
$tokenContext = new AuthorizationCodeContext(
$tenantId,
$clientId,
$clientSecret,
$authorizationCode,
$redirectUri);
$graphClient = new GraphServiceClient($tokenContext, $scopes);
Incluya use
instrucciones para Microsoft\Graph\GraphRequestAdapter
, Microsoft\Graph\GraphServiceClient
y Microsoft\Kiota\Abstractions\Authentication\BaseBearerTokenAuthenticationProvider
para ejecutar este código.
scopes = ['User.Read']
# Multi-tenant apps can use "common",
# single-tenant apps must use the tenant ID from the Azure portal
tenant_id = 'common'
# Values from app registration
client_id = 'YOUR_CLIENT_ID'
# azure.identity
credential = DeviceCodeCredential(
tenant_id=tenant_id,
client_id=client_id)
graph_client = GraphServiceClient(credential, scopes)
Incluya import
instrucciones para DeviceCodeCredential
desde azure.identity
y GraphServiceClient
desde msgraph.graph_service_client
para ejecutar este código.
// @azure/identity
const credential = new DeviceCodeCredential({
tenantId: 'YOUR_TENANT_ID',
clientId: 'YOUR_CLIENT_ID',
userPromptCallback: (info) => {
console.log(info.message);
},
});
// @microsoft/microsoft-graph-client/authProviders/azureTokenCredentials
const authProvider = new TokenCredentialAuthenticationProvider(credential, {
scopes: ['User.Read'],
});
const graphClient = Client.initWithMiddleware({ authProvider: authProvider });
Incluya import
instrucciones para DeviceCodeCredential
desde @azure/identity
, Client
desde @microsoft/microsoft-graph-client
y TokenCredentialAuthenticationProvider
desde @microsoft/microsoft-graph-client/authProviders/azureTokenCredentials
para ejecutar este código.