Microsoft.Identity.Web ile daemon uygulamaları ve aracı kimlikleri oluşturun.

Bu makalede, Microsoft.Identity.Web kullanarak daemon uygulamaları, arka plan hizmetleri ve otonom aracılar oluşturacaksınız. Bu uygulamalar kullanıcı etkileşimi olmadan çalışır ve uygulama kimliği (istemci kimlik bilgileri) veya aracı kimlikleri kullanarak kimlik doğrulaması yapar.

Desteklenen senaryoları anlama

Microsoft. Identity.Web üç etkileşimli olmayan uygulama türünü destekler:

Senaryo Kimlik Doğrulama Türü Belirteç Türü Kullanım Örneği
Standart Daemon İstemci kimlik bilgileri (gizli anahtar/sertifika) Uygulamaya özel erişim belirteci Arka plan hizmetleri, zamanlanmış işler, veri işleme
Otonom Aracı İstemci kimlik bilgileriyle aracı kimliği Aracı için uygulamaya özel erişim belirteci Copilot aracıları, bir ajan kimliği adına hareket eden otonom hizmetler. (Genellikle korumalı bir Web API'sinde)
Aracı Kullanıcı Kimliği Aracı kullanıcı kimliği İstemci kimlik bilgileriyle aracı kullanıcı kimliği Temsilci kullanıcı kimliği adına hareket eden otonom hizmetler. (Genellikle korumalı bir Web API'sinde)

Kullanmaya başlama

Önkoşullar

Başlamadan önce aşağıdakilere sahip olduğunuzdan emin olun:

  • .NET 8.0 veya üzeri
  • Microsoft Entra için istemci kimlik bilgileri (istemci gizli anahtarı veya sertifikası) ile uygulama kaydı
  • Aracı senaryoları için: Microsoft Entra kiracınızda yapılandırılmış aracı kimlikleri

Paketleri yükleme

Projenize gerekli NuGet paketlerini ekleyin:

dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Extensions.Hosting

Yapılandırma yaklaşımı seçme

Microsoft. Identity.Web, daemon uygulamalarını yapılandırmak için iki yol sağlar:

En iyileri: Hızlı prototipler, konsol uygulamaları, test ve basit daemon hizmetleri.

Aşağıdaki kod bir TokenAcquirerFactory oluşturur, aşağı akış API'lerini ve Microsoft Graph yapılandırır ve Graph API çağırır:

using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;

// Get the token acquirer factory instance
var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();

// Configure downstream API and Microsoft Graph (optional)
tokenAcquirerFactory.Services.AddDownstreamApis(
    tokenAcquirerFactory.Configuration.GetSection("DownstreamApis"))
    .AddMicrosoftGraph();

var serviceProvider = tokenAcquirerFactory.Build();

// Call Microsoft Graph
var graphClient = serviceProvider.GetRequiredService<GraphServiceClient>();
var users = await graphClient.Users.GetAsync();

Avantajlar:

  • Minimum şablon kod
  • Otomatik olarak yüklenir appsettings.json
  • Basit senaryolar için mükemmel
  • Tek satırlı başlatma

Dezavantaj -ları:

  • Paralel çalışan (singleton) testler için uygun değildir.

En iyileri: Üretim uygulamaları, karmaşık senaryolar, bağımlılık ekleme, test edilebilirlik.

Aşağıdaki kod kimlik doğrulaması, belirteç alma, önbelleğe alma ve arka plan hizmetini yapılandırmak için .NET Genel Ana Bilgisayarı kullanır:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        // Configure authentication
        services.Configure<MicrosoftIdentityApplicationOptions>(
            context.Configuration.GetSection("AzureAd"));

        // Add token acquisition (true = singleton lifetime)
        services.AddTokenAcquisition(true);

        // Add token cache (in-memory for development)
        services.AddInMemoryTokenCaches();

        // Add HTTP client for API calls
        services.AddHttpClient();

        // Add Microsoft Graph (optional)
        services.AddMicrosoftGraph();

        // Add your background service
        services.AddHostedService<DaemonWorker>();
    })
    .Build();

await host.RunAsync();

Avantajlar:

  • Yapılandırma sağlayıcıları üzerinde tam denetim
  • Yapıcı enjeksiyonu ile daha iyi test edilebilirlik
  • ASP.NET Core barındırma modeliyle tümleşir
  • Karmaşık senaryoları (birden çok kimlik doğrulama şeması) destekler
  • Üretime hazır mimari
  • Paralel test yürütmeyi destekler (test başına yalıtılmış hizmet sağlayıcısı)

Uyarı

Parametre trueAddTokenAcquisition(true), hizmetin singleton (uygulama ömrü için tek örnek) olarak kaydedildiği anlamına gelir. Web uygulamalarında kapsamı belirlenmiş yaşam süresi için kullanın false .

Öneri: Prototipler ve tek iş parçacıklı testler için TokenAcquirerFactory ile başlayın. Üretim uygulamaları oluştururken veya paralel testler çalıştırırken tam ServiceCollection desene geçiş yapın.


Standart daemon uygulamalarını yapılandırma

Standart daemon uygulamaları , istemci kimlik bilgilerini (istemci gizli dizisi veya sertifika) kullanarak kimlik doğrulaması yapar ve API'leri çağırmak için yalnızca uygulama erişim belirteçleri alır.

Kimlik doğrulaması ayarlarını yapılandırma

aşağıdaki yapılandırmayı appsettings.json dosyanıza ekleyin. İster istemci sırrı ister sertifika (üretim için önerilir) kullanabilirsiniz:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "your-tenant-id",
    "ClientId": "your-client-id",

    "ClientSecret": "your-client-secret",

    "ClientCredentials": [
      // Option 1: Client Secret
      {
        "SourceType": "ClientSecret",
        "ClientSecret": "your-client-secret",
      },
      // Option 2: Certificate (recommended for production)
      {
        "SourceType": "StoreWithDistinguishedName",
        "CertificateStorePath": "CurrentUser/My",
        "CertificateDistinguishedName": "CN=DaemonAppCert"
      }
      // More options: https://aka.ms/ms-id-web/client-credentials
    ]
  }
}

Önemli: Öğenizi çıkış dizinine kopyalanacak şekilde appsettings.json ayarlayın. Aşağıdakini dosyanıza .csproj ekleyin:

<ItemGroup>
  <None Update="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

ASP.NET Core uygulamalar bu dosyayı otomatik olarak kopyalar, ancak daemon uygulamaları (ve OWIN uygulamaları) kopyalamaz.

Hizmet yapılandırmasını ayarlama

Aşağıdaki Program.cs kodu, Microsoft kimlik seçeneklerini, belirteç almayı, önbelleğe almayı ve barındırılan arka plan hizmetini kaydeder.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        IConfiguration configuration = context.Configuration;

        // Configure Microsoft Identity options
        services.Configure<MicrosoftIdentityApplicationOptions>(
            configuration.GetSection("AzureAd"));

        // Add token acquisition (true = singleton)
        services.AddTokenAcquisition(true);

        // Add token cache
        services.AddInMemoryTokenCaches(); // For development
        // services.AddDistributedTokenCaches(); // For production

        // Add HTTP client
        services.AddHttpClient();

        // Add Microsoft Graph SDK (optional)
        services.AddMicrosoftGraph();

        // Add your background service
        services.AddHostedService<DaemonWorker>();
    })
    .Build();

await host.RunAsync();

Microsoft Graph'ı Çağır

Aşağıdaki DaemonWorker.cs sınıfı, yinelenen bir zamanlamaya göre kullanıcıları listelemek için Graph SDK'sını kullanır:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Microsoft.Identity.Abstractions;

public class DaemonWorker : BackgroundService
{
    private readonly GraphServiceClient _graphClient;
    private readonly ILogger<DaemonWorker> _logger;

    public DaemonWorker(
        GraphServiceClient graphClient,
        ILogger<DaemonWorker> logger)
    {
        _graphClient = graphClient;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                // Call Microsoft Graph with app-only permissions
                var users = await _graphClient.Users
                    .GetAsync(cancellationToken: stoppingToken);

                _logger.LogInformation($"Found {users?.Value?.Count} users");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error calling Microsoft Graph");
            }

            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
        }
    }
}

IAuthorizationHeaderProvider kullanın

HTTP çağrıları üzerinde daha fazla denetim için, yetkilendirme üst bilgilerini el ile oluşturmak için kullanın IAuthorizationHeaderProvider :

using Microsoft.Identity.Abstractions;

public class DaemonService
{
    private readonly IAuthorizationHeaderProvider _authProvider;
    private readonly HttpClient _httpClient;

    public DaemonService(
        IAuthorizationHeaderProvider authProvider,
        IHttpClientFactory httpClientFactory)
    {
        _authProvider = authProvider;
        _httpClient = httpClientFactory.CreateClient();
    }

    public async Task<string> CallApiAsync()
    {
        // Get authorization header for app-only access
        string authHeader = await _authProvider
            .CreateAuthorizationHeaderForAppAsync(
                scopes: "https://graph.microsoft.com/.default");

        // Add to HTTP request
        _httpClient.DefaultRequestHeaders.Clear();
        _httpClient.DefaultRequestHeaders.Add("Authorization", authHeader);

        var response = await _httpClient.GetStringAsync(
            "https://graph.microsoft.com/v1.0/users");

        return response;
    }
}

Ayrıca bakınız Aşağı akış API'lerini çağırma Microsoft Identity Web'in aşağı akış API'lerini çağırmak için önerdiği tüm yollar hakkında bilgi edinin.


Otonom aracıları yapılandırma (aracı kimliği)

Otonom aracılar yalnızca uygulama belirteçlerini almak için aracı kimliklerini kullanır. Bu şablon, Copilot senaryoları ve otonom hizmetler için faydalıdır.

Uyarı

Microsoft, aşağı akış API'lerini çağıran aracıların uygulama belirteci edindiğinde bile bunu korumalı web API'lerinin içinden gerçekleştirmesini önerir.

Aracı hizmetlerini yapılandırma

Aşağıdaki kod, bellek içi yapılandırmayı kullanarak kimlik doğrulaması, belirteç alma ve aracı kimliği desteğini ayarlar:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;

var services = new ServiceCollection();

// Configuration
var configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(new Dictionary<string, string?>
    {
        ["AzureAd:Instance"] = "https://login.microsoftonline.com/",
        ["AzureAd:TenantId"] = "your-tenant-id",
        ["AzureAd:ClientId"] = "your-agent-app-client-id",
        ["AzureAd:ClientCredentials:0:SourceType"] = "StoreWithDistinguishedName",
        ["AzureAd:ClientCredentials:0:CertificateStorePath"] = "CurrentUser/My",
        ["AzureAd:ClientCredentials:0:CertificateDistinguishedName"] = "CN=YourCert"
    })
    .Build();

services.AddSingleton<IConfiguration>(configuration);

// Configure Microsoft Identity
services.Configure<MicrosoftIdentityApplicationOptions>(
    configuration.GetSection("AzureAd"));

services.AddTokenAcquisition(true);
services.AddInMemoryTokenCaches();
services.AddHttpClient();
services.AddMicrosoftGraph();

// Add agent identities support
services.AddAgentIdentities();

var serviceProvider = services.BuildServiceProvider();

Aracı kimliğini kullanarak belirteç edinin

Aracı hizmetlerini yapılandırdıktan sonra IAuthorizationHeaderProvider veya Microsoft Graph SDK'sını kullanarak belirteçleri alın:

using Microsoft.Identity.Abstractions;
using Microsoft.Graph;

// Your agent identity GUID
string agentIdentityId = "d84da24a-2ea2-42b8-b5ab-8637ec208024";

// Option 1: Using IAuthorizationHeaderProvider
IAuthorizationHeaderProvider authProvider =
    serviceProvider.GetRequiredService<IAuthorizationHeaderProvider>();

var options = new AuthorizationHeaderProviderOptions()
    .WithAgentIdentity(agentIdentityId);

string authHeader = await authProvider.CreateAuthorizationHeaderForAppAsync(
    scopes: "https://graph.microsoft.com/.default",
    options);

// Option 2: Using Microsoft Graph SDK
GraphServiceClient graphClient =
    serviceProvider.GetRequiredService<GraphServiceClient>();

var applications = await graphClient.Applications.GetAsync(request =>
{
    request.Options.WithAuthenticationOptions(authOptions =>
    {
        authOptions.WithAgentIdentity(agentIdentityId);
    });
});

Tam bir otonom aracı örneğini gözden geçirin

Aşağıdaki sınıf, aracı kimliği belirtecinin edinilmesi ve Graph API çağrılarının modüler bir hizmete dönüştürülmesini kapsar.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;

public class AutonomousAgentService
{
    private readonly GraphServiceClient _graphClient;
    private readonly IAuthorizationHeaderProvider _authProvider;
    private readonly string _agentIdentityId;

    public AutonomousAgentService(
        string agentIdentityId,
        IServiceProvider serviceProvider)
    {
        _agentIdentityId = agentIdentityId;
        _graphClient = serviceProvider.GetRequiredService<GraphServiceClient>();
        _authProvider = serviceProvider.GetRequiredService<IAuthorizationHeaderProvider>();
    }

    public async Task<string> GetAuthorizationHeaderAsync()
    {
        var options = new AuthorizationHeaderProviderOptions()
            .WithAgentIdentity(_agentIdentityId);

        return await _authProvider.CreateAuthorizationHeaderForAppAsync(
            "https://graph.microsoft.com/.default",
            options);
    }

    public async Task<IEnumerable<Application>> ListApplicationsAsync()
    {
        var apps = await _graphClient.Applications.GetAsync(request =>
        {
            request.Options.WithAuthenticationOptions(options =>
            {
                options.WithAgentIdentity(_agentIdentityId);
            });
        });

        return apps?.Value ?? Enumerable.Empty<Application>();
    }
}

Aracı kullanıcı kimliğini yapılandırma

Aracı kullanıcı kimliği, aracıların temsilci izinleri olan bir aracı kullanıcısı adına işlem yapmasına olanak tanır. Kendi posta kutusuna veya kullanıcıya özel diğer kaynaklara ihtiyaç duyan aracılar için bu kalıbı kullanın.

Önkoşullar

Aracı kullanıcı kimliğini kullanmak için şunları yapmanız gerekir:

  • Microsoft Entra ID'de kayıtlı ajan planı
  • Aracı kimliği oluşturuldu ve aracı uygulamasına bağlandı
  • Aracı kimliğiyle ilişkili aracı kullanıcı kimliği

Aracı kullanıcı hizmetlerini yapılandırma

Aşağıdaki kod, aracı uygulama kimliğini bir sertifika kimlik bilgileriyle yapılandırıp gerekli hizmetleri kaydeder:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Web;
using System.Security.Cryptography.X509Certificates;

var services = new ServiceCollection();

// Configure agent application
services.Configure<MicrosoftIdentityApplicationOptions>(options =>
{
    options.Instance = "https://login.microsoftonline.com/";
    options.TenantId = "your-tenant-id";
    options.ClientId = "your-agent-app-client-id";

    // Use certificate for agent authentication
    options.ClientCredentials = new[]
    {
        CertificateDescription.FromStoreWithDistinguishedName(
            "CN=YourCertificate",
            StoreLocation.CurrentUser,
            StoreName.My)
    };
});

// Add services (true = singleton)
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddTokenAcquisition(true);
services.AddInMemoryTokenCaches();
services.AddHttpClient();
services.AddMicrosoftGraph();
services.AddAgentIdentities();

var serviceProvider = services.BuildServiceProvider();

Aracı kimliğiyle kullanıcı belirteçleri alma

Hedef kullanıcıyı UPN veya nesne kimliğine göre tanımlayabilirsiniz.

Kullanıcı adına göre (UPN)

using Microsoft.Identity.Abstractions;
using Microsoft.Graph;

string agentIdentityId = "your-agent-identity-id";
string userUpn = "user@yourtenant.onmicrosoft.com";

// Get authorization header
IAuthorizationHeaderProvider authProvider =
    serviceProvider.GetRequiredService<IAuthorizationHeaderProvider>();

var options = new AuthorizationHeaderProviderOptions()
    .WithAgentUserIdentity(
        agentApplicationId: agentIdentityId,
        username: userUpn);

string authHeader = await authProvider.CreateAuthorizationHeaderForUserAsync(
    scopes: new[] { "https://graph.microsoft.com/.default" },
    options);

// Or use Microsoft Graph SDK
GraphServiceClient graphClient =
    serviceProvider.GetRequiredService<GraphServiceClient>();

var me = await graphClient.Me.GetAsync(request =>
{
    request.Options.WithAuthenticationOptions(options =>
        options.WithAgentUserIdentity(agentIdentityId, userUpn));
});

Kullanıcı Nesne Kimliğine göre

string agentIdentityId = "your-agent-identity-id";
Guid userObjectId = Guid.Parse("user-object-id");

var options = new AuthorizationHeaderProviderOptions()
    .WithAgentUserIdentity(
        agentApplicationId: agentIdentityId,
        userId: userObjectId);

string authHeader = await authProvider.CreateAuthorizationHeaderForUserAsync(
    scopes: new[] { "https://graph.microsoft.com/.default" },
    options);

// With Graph SDK
var me = await graphClient.Me.GetAsync(request =>
{
    request.Options.WithAuthenticationOptions(options =>
        options.WithAgentUserIdentity(agentIdentityId, userObjectId));
});

ClaimsPrincipal ile belirteçleri önbelleğe alma

Daha iyi performans için bir ClaimsPrincipal örneği geçirerek kullanıcı belirteçlerini önbelleğe alın. İlk çağrı, temeli uid ve utid hak talepleri ile doldurur; sonraki çağrılar önbelleğe alınmış belirteci yeniden kullanır:

using System.Security.Claims;
using Microsoft.Identity.Abstractions;

// First call - creates cache entry
ClaimsPrincipal userPrincipal = new ClaimsPrincipal();

string authHeader = await authProvider.CreateAuthorizationHeaderForUserAsync(
    scopes: new[] { "https://graph.microsoft.com/.default" },
    options,
    userPrincipal);

// ClaimsPrincipal now has uid and utid claims for caching
bool hasUserId = userPrincipal.HasClaim(c => c.Type == "uid");
bool hasTenantId = userPrincipal.HasClaim(c => c.Type == "utid");

// Subsequent calls - uses cache
authHeader = await authProvider.CreateAuthorizationHeaderForUserAsync(
    scopes: new[] { "https://graph.microsoft.com/.default" },
    options,
    userPrincipal); // Reuse the same principal

Kiracıyı geçersiz kılma

Çok kiracılı senaryolar için çalışma zamanında kiracıyı geçersiz kılabilirsiniz. Bu, uygulama ile "common" yapılandırıldığında ancak belirli bir kiracıyı hedeflemesi gerektiğinde kullanışlıdır:

var options = new AuthorizationHeaderProviderOptions()
    .WithAgentUserIdentity(agentIdentityId, userUpn);

// Override tenant (useful when app is configured with "common")
options.AcquireTokenOptions.Tenant = "specific-tenant-id";

string authHeader = await authProvider.CreateAuthorizationHeaderForUserAsync(
    scopes: new[] { "https://graph.microsoft.com/.default" },
    options);

// With Graph SDK
var me = await graphClient.Me.GetAsync(request =>
{
    request.Options.WithAuthenticationOptions(options =>
    {
        options.WithAgentUserIdentity(agentIdentityId, userUpn);
        options.AcquireTokenOptions.Tenant = "specific-tenant-id";
    });
});

Eksiksiz bir aracı kullanıcı kimliği örneğini gözden geçirin

Aşağıdaki sınıf, aracı kullanıcı kimliğini kullanarak kullanıcı profillerini ve yetkilendirme üst bilgilerini almak için yöntemler sağlar:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Graph;
using Microsoft.Identity.Abstractions;
using System.Security.Claims;

public class AgentUserService
{
    private readonly IAuthorizationHeaderProvider _authProvider;
    private readonly GraphServiceClient _graphClient;
    private readonly string _agentIdentityId;

    public AgentUserService(
        string agentIdentityId,
        IServiceProvider serviceProvider)
    {
        _agentIdentityId = agentIdentityId;
        _authProvider = serviceProvider.GetRequiredService<IAuthorizationHeaderProvider>();
        _graphClient = serviceProvider.GetRequiredService<GraphServiceClient>();
    }

    public async Task<User> GetUserProfileAsync(string userUpn)
    {
        var me = await _graphClient.Me.GetAsync(request =>
        {
            request.Options.WithAuthenticationOptions(options =>
                options.WithAgentUserIdentity(_agentIdentityId, userUpn));
        });

        return me!;
    }

    public async Task<User> GetUserProfileByIdAsync(Guid userObjectId)
    {
        var me = await _graphClient.Me.GetAsync(request =>
        {
            request.Options.WithAuthenticationOptions(options =>
                options.WithAgentUserIdentity(_agentIdentityId, userObjectId));
        });

        return me!;
    }

    public async Task<string> GetAuthHeaderForUserAsync(
        string userUpn,
        ClaimsPrincipal? cachedPrincipal = null)
    {
        var options = new AuthorizationHeaderProviderOptions()
            .WithAgentUserIdentity(_agentIdentityId, userUpn);

        return await _authProvider.CreateAuthorizationHeaderForUserAsync(
            scopes: new[] { "https://graph.microsoft.com/.default" },
            options,
            cachedPrincipal ?? new ClaimsPrincipal());
    }
}

Yeniden kullanılabilir hizmet yapılandırması oluşturma

Uzantı yöntemi tanımlama

Uygulamanız genelinde aracı kimliği yapılandırmasını kapsüllemek için yeniden kullanılabilir bir uzantı yöntemi oluşturun:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;

public static class ServiceCollectionExtensions
{
    public static IServiceProvider ConfigureServicesForAgentIdentities(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        // Add configuration
        services.AddSingleton(configuration);

        // Configure Microsoft Identity options
        services.Configure<MicrosoftIdentityApplicationOptions>(
            configuration.GetSection("AzureAd"));

        services.AddTokenAcquisition(true);

        // Add token caching
        services.AddInMemoryTokenCaches();

        // Add HTTP client
        services.AddHttpClient();

        // Add Microsoft Graph (optional)
        services.AddMicrosoftGraph();

        // Add agent identities support
        services.AddAgentIdentities();

        return services.BuildServiceProvider();
    }
}

Uzantı yöntemini kullanma

Hizmetleri tek bir satırda yapılandırmak için uzantı yöntemini çağırın:

var services = new ServiceCollection();
var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

var serviceProvider = services.ConfigureServicesForAgentIdentities(configuration);

API'leri çağırma

Bu bölümde, üç kimlik doğrulama deseninin her birini kullanarak API'lerin nasıl çağrılması gösterilmektedir.

Microsoft Graph'ı Çağır

Aşağıdaki örneklerde Microsoft Graph'ın standart bir hizmet, otonom bir aracı ve bir aracı kullanıcı kimliği olarak çağrılması gösterilmektedir.

using Microsoft.Graph;

GraphServiceClient graphClient =
    serviceProvider.GetRequiredService<GraphServiceClient>();

// Standard daemon (app-only)
var users = await graphClient.Users.GetAsync();

// Autonomous agent (app-only with agent identity)
var apps = await graphClient.Applications.GetAsync(request =>
{
    request.Options.WithAuthenticationOptions(options =>
    {
        options.WithAgentIdentity("agent-identity-id");
        options.RequestAppToken = true;
    });
});

// Agent user identity (delegated with user context)
var me = await graphClient.Me.GetAsync(request =>
{
    request.Options.WithAuthenticationOptions(options =>
        options.WithAgentUserIdentity("agent-identity-id", "user@tenant.com"));
});

IDownstreamApi ile özel API'leri çağırma

Üç kimlik doğrulama deseninin herhangi biriyle kendi korumalı API'lerinizi çağırmak için kullanın IDownstreamApi :

using Microsoft.Identity.Abstractions;

IDownstreamApi downstreamApi =
    serviceProvider.GetRequiredService<IDownstreamApi>();

// Standard daemon
var result = await downstreamApi.GetForAppAsync<ApiResponse>(
    serviceName: "MyApi",
    options => options.RelativePath = "api/data");

// With agent identity
var result = await downstreamApi.GetForAppAsync<ApiResponse>(
    serviceName: "MyApi",
    options =>
    {
        options.RelativePath = "api/data";
        options.WithAgentIdentity("agent-identity-id");
    });

// Agent user identity
var result = await downstreamApi.GetForUserAsync<ApiResponse>(
    serviceName: "MyApi",
    options =>
    {
        options.RelativePath = "api/data";
        options.WithAgentUserIdentity("agent-identity-id", "user@tenant.com");
    });

El ile HTTP çağrıları yapma

HTTP istekleri üzerinde tam denetime ihtiyacınız olduğunda doğrudan kullanın IAuthorizationHeaderProvider :

using Microsoft.Identity.Abstractions;

IAuthorizationHeaderProvider authProvider =
    serviceProvider.GetRequiredService<IAuthorizationHeaderProvider>();

HttpClient httpClient = new HttpClient();

// Standard daemon
string authHeader = await authProvider.CreateAuthorizationHeaderForAppAsync(
    "https://graph.microsoft.com/.default");

httpClient.DefaultRequestHeaders.Add("Authorization", authHeader);
var response = await httpClient.GetStringAsync("https://graph.microsoft.com/v1.0/users");

// With agent identity
var options = new AuthorizationHeaderProviderOptions()
    .WithAgentIdentity("agent-identity-id");

authHeader = await authProvider.CreateAuthorizationHeaderForAppAsync(
    "https://graph.microsoft.com/.default",
    options);

// Agent user identity
var userOptions = new AuthorizationHeaderProviderOptions()
    .WithAgentUserIdentity("agent-identity-id", "user@tenant.com");

authHeader = await authProvider.CreateAuthorizationHeaderForUserAsync(
    new[] { "https://graph.microsoft.com/.default" },
    userOptions);

Belirteç önbelleğini yapılandırma

Ortamınıza göre bir önbelleğe alma stratejisi seçin.

Geliştirme: Bellek içi önbellek

Yerel geliştirme ve test için bellek içi önbelleğe alma özelliğini kullanın:

services.AddInMemoryTokenCaches();

Üretim: Dağıtılmış önbellek

Üretimde, uygulama yeniden başlatmaları ve ölçeği genişletme örnekleri arasında belirteçleri kalıcı hale getirmek için dağıtılmış bir önbellek kullanın.

SQL Server

Belirteçleri bir SQL Server tablosunda depolayın:

services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = configuration["ConnectionStrings:TokenCache"];
    options.SchemaName = "dbo";
    options.TableName = "TokenCache";
});
services.AddDistributedTokenCaches();

Redis

Yüksek performanslı, dağıtılmış belirteç önbelleğe alma için Redis kullanın:

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = configuration["Redis:ConnectionString"];
    options.InstanceName = "TokenCache_";
});
services.AddDistributedTokenCaches();

Cosmos DB

Genel olarak dağıtılmış belirteç önbelleğe alma için Cosmos DB kullanın:

services.AddCosmosDbTokenCaches(options =>
{
    options.CosmosDbConnectionString = configuration["CosmosDb:ConnectionString"];
    options.DatabaseId = "TokenCache";
    options.ContainerId = "Tokens";
});

Daha fazla bilgi edinin:Belirteç Önbelleği Yapılandırması


Azure örneklerini keşfetme

Microsoft, daemon uygulama desenlerini gösteren örnekler sağlar.

Örnek deposu

active-directory-dotnetcore-daemon-v2

Bu depo birden çok senaryo içerir:

Örnek Tanım Bağlantı
1-Call-MSGraph İstemci kimlik bilgilerini kullanarak Microsoft Graph'a temel daemon araması Örneği Görüntüle
2-Call-OwnApi Kendi korumalı web API'nizi çağıran Daemon Örneği Görüntüle
3 - KeyVault'u Kullanma Sertifika depolama için Azure Key Vault kullanan daemon Örneği Görüntüle
4-Çok Kiracılı Çok kiracılı daemon uygulaması Örneği Görüntüle
5-Call-MSGraph-ManagedIdentity Azure'da Yönetilen Kimlik kullanan Daemon Örneği Görüntüle

Örnek desenleri üretim desenleri ile karşılaştırma

Azure örnekleri basitlik için TokenAcquirerFactory.GetDefaultInstance() kullanır; simple konsol uygulamaları, prototipler ve testler için önerilen yaklaşım. Bu kılavuz her iki deseni de gösterir:

TokenAcquirerFactory Deseni (Azure Örnekleri):

// Simple, perfect for prototypes and tests
var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
tokenAcquirerFactory.Services.AddDownstreamApi("MyApi", ...);
var serviceProvider = tokenAcquirerFactory.Build();

Full ServiceCollection Deseni (Üretim Uygulamaları):

// More control, testable, follows DI best practices
var services = new ServiceCollection();
services.AddTokenAcquisition(true); // true = singleton
services.Configure<MicrosoftIdentityApplicationOptions>(...);
var serviceProvider = services.BuildServiceProvider();

Hangi kullanım zamanı:

  • Kullanın TokenAcquirerFactory için: Konsol uygulamaları, hızlı prototipler, birim testleri, basit daemon hizmetleri
  • ServiceCollection için kullanın: Üretim uygulamaları, ASP.NET Core tümleştirmesi, karmaşık DI senaryoları, IHostedService ile arka plan hizmetleri

Her iki yaklaşım da tam olarak desteklenir ve üretime hazırdır. Uygulamanızın karmaşıklığı ve tümleştirme gereksinimlerine göre seçin.


Sık karşılaşılan hataları giderme

AADSTS700016: Uygulama bulunamadı

Neden: Geçersiz ClientId veya uygulamanın kiracıda kayıtlı olmaması.

Solution: Yapılandırmanızdaki ClientId Microsoft Entra uygulama kaydınızla eşleştiklerini doğrulayın.

AADSTS7000215: Geçersiz istemci sırrı

Neden: İstemci sırrı yanlış, süresi dolmuş veya yapılandırılmamış.

Çözüm:

  • Azure portalı üzerindeki gizli anahtarın yapılandırmanızla eşleştiğini doğrulayın
  • Gizli son kullanma tarihini kontrol et
  • Üretim için sertifikaları kullanmayı göz önünde bulundurun

AADSTS700027: İstemci onayı geçersiz imza içeriyor

Neden: Sertifika bulunamadı, süresi doldu veya özel anahtar erişilebilir değil.

Çözüm:

  • Sertifikanın doğru sertifika deposuna yüklendiğini doğrulama
  • Sertifika ayırt edici adının yapılandırmayla eşleşir olup olmadığını denetleyin
  • Uygulamanın özel anahtarı okuma izni olduğundan emin olun
  • Bkz. Sertifika Yapılandırma Kılavuzu

AADSTS650052: Uygulamanın bir hizmete erişmesi gerekiyor

Neden: Gerekli API izinleri verilmedi veya yönetici onayı eksik.

Çözüm:

  1. Azure portalına gidin → Uygulama kayıtları → Uygulamanız → API izinleri
  2. Gerekli izinleri ekleme (örneğin, Microsoft Graph için User.Read.All)
  3. "Yönetici onayı ver" düğmesine tıklayın

Temsilci kimliği hataları

AADSTS50105: Oturum açmış kullanıcı bir role atanmadı

Neden: Aracı kimliği düzgün yapılandırılmadı veya uygulamaya atanmadı.

Çözüm:

  • Microsoft Entra ID'de temsilci kimliğinin mevcut olduğunu doğrulayın
  • Ajan kimliğinin uygulamanızla bağlantılı olduğundan emin olun
  • Aracı kimliğinin gerekli izinlere sahip olup olmadığını denetleyin

Alınan ancak yanlış izinlere sahip belirteçler

Neden: Aracı kullanıcı kimliğini kullanma ancak uygulama izinleri isteme veya tam tersi.

Çözüm:

  • Yalnızca uygulama belirteçleri için: CreateAuthorizationHeaderForAppAsync ve WithAgentIdentity ile kullanın
  • Temsilci belirteçleri için: CreateAuthorizationHeaderForUserAsync ile WithAgentUserIdentity kullanın
  • API izinlerinin belirteç türüyle eşleştiğinden emin olun (uygulama veya temsilci)

Belirteç önbelleğe alma sorunları

Sorun: Belirteçler önbelleğe alınmaz ve bu da her seferinde yeni bir alıma zorlar.

Çözüm:

  • Aracı kullanıcı kimliği için: Çağrılar arasında aynı ClaimsPrincipal örneği yeniden kullanma
  • Dağıtılmış önbellek bağlantısını doğrulama (Redis/SQL kullanıyorsanız)
  • Önbellek işlemlerini görmek için hata ayıklama günlüğünü etkinleştirme

Ayrıntılı tanılama:Günlük ve Tanılama Kılavuzu