Клиент Microsoft Graph предназначен для упрощения вызовов к Microsoft Graph. Для времени существования приложения можно использовать один экземпляр клиента. Сведения о том, как добавить и установить пакет клиента Microsoft Graph в проект, см. в разделе Установка пакета SDK.
В следующих примерах кода показано, как создать экземпляр клиента Microsoft Graph с поставщиком проверки подлинности на поддерживаемых языках. Поставщик проверки подлинности обрабатывает получение маркеров доступа для приложения.
Для каждого языка и платформы доступно множество различных поставщиков проверки подлинности. Разные поставщики проверки подлинности поддерживают разные клиентские сценарии. Дополнительные сведения о поставщике и параметрах, подходящих для вашего сценария, см. в разделе Выбор поставщика проверки подлинности.
Идентификатор клиента — это идентификатор регистрации приложения, который создается при регистрации приложения в портал 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);
Включите using
инструкции для и Microsoft.Graph
для Azure.Identity
выполнения этого кода.
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"})
Включите "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
и graph "github.com/microsoftgraph/msgraph-sdk-go"
в блок импорта для выполнения этого кода.
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);
Включите import
инструкции для com.azure.identity.DeviceCodeCredential
, com.azure.identity.DeviceCodeCredentialBuilder
и com.microsoft.graph.serviceclient.GraphServiceClient
для выполнения этого кода.
$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);
Включите use
инструкции для Microsoft\Graph\GraphRequestAdapter
, Microsoft\Graph\GraphServiceClient
и Microsoft\Kiota\Abstractions\Authentication\BaseBearerTokenAuthenticationProvider
для выполнения этого кода.
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)
Включите import
инструкции для DeviceCodeCredential
из azure.identity
и GraphServiceClient
от msgraph.graph_service_client
, чтобы выполнить этот код.
// @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 });
Включите import
инструкции для from @azure/identity
DeviceCodeCredential
, Client
from @microsoft/microsoft-graph-client
и TokenCredentialAuthenticationProvider
from@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials
, чтобы выполнить этот код.