O cliente do Microsoft Graph foi concebido para simplificar a efetuar chamadas para o Microsoft Graph. Pode utilizar uma única instância de cliente para a duração da aplicação. Para obter informações sobre como adicionar e instalar o pacote de cliente do Microsoft Graph no seu projeto, veja Instalar o SDK.
Os exemplos de código seguintes mostram como criar uma instância de um cliente do Microsoft Graph com um fornecedor de autenticação nos idiomas suportados. O fornecedor de autenticação processa a aquisição de tokens de acesso para a aplicação.
Estão disponíveis muitos fornecedores de autenticação diferentes para cada idioma e plataforma. Os diferentes fornecedores de autenticação suportam diferentes cenários de cliente. Para obter detalhes sobre que fornecedor e opções são adequados para o seu cenário, veja Escolher um Fornecedor de Autenticação.
O ID de cliente é o ID de registo da aplicação que é gerado quando regista a sua aplicação no portal do Azure.
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);
Inclua using instruções para Azure.Identity e Microsoft.Graph para executar 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"})
Inclua "github.com/Azure/azure-sdk-for-go/sdk/azidentity" e graph "github.com/microsoftgraph/msgraph-sdk-go" no seu bloco de importação para executar 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);
Inclua import instruções para com.azure.identity.DeviceCodeCredential, com.azure.identity.DeviceCodeCredentialBuildere com.microsoft.graph.serviceclient.GraphServiceClient para executar 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);
Inclua use instruções para Microsoft\Graph\GraphRequestAdapter, Microsoft\Graph\GraphServiceCliente Microsoft\Kiota\Abstractions\Authentication\BaseBearerTokenAuthenticationProvider para executar 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)
Inclua import instruções para DeviceCodeCredential de azure.identity e GraphServiceClient de msgraph.graph_service_client para executar 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 });
Inclua import instruções para DeviceCodeCredential de @azure/identity, Client de @microsoft/microsoft-graph-cliente TokenCredentialAuthenticationProvider de @microsoft/microsoft-graph-client/authProviders/azureTokenCredentials para executar este código.