You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core API调用MS Graph获取Azure AD用户信息遇阻求助

Fixing Single-Tenant Azure AD + Microsoft Graph Issues in .NET Core API

Hey there, let's work through your problem step by step. I see you're stuck getting your single-tenant .NET Core API to call Microsoft Graph, and the existing tutorials either don't fit your single-tenant setup or throw errors even after adjusting settings.

First, Let's Diagnose Your Current Issues

  • Multi-Tenant Tutorial Mismatch: The first sample you tried is built for multi-tenant apps, which uses different authentication logic than single-tenant scenarios—so that's why it didn't align with your needs.
  • Preview NuGet & HTTPS Error: The second tutorial relies on unstable preview packages, and your RequireHttpsMetadata=false fix didn't resolve the error because there's a misconfiguration in how you're mixing authentication and Microsoft Graph integration in your Startup.cs.

Step 1: Switch to Stable NuGet Packages

First, uninstall those preview packages and install these official, stable packages via NuGet:

  • Microsoft.Identity.Web
  • Microsoft.Identity.Web.MicrosoftGraph

These are maintained directly by Microsoft and have full support for single-tenant use cases.


Step 2: Fix Your Startup.cs Configuration

Your current code mixes web app authentication methods (AddSignIn, AddWebAppCallsProtectedWebApi) with API-specific logic—this is the core issue. For a backend API, you need to use AddProtectedWebApi instead. Here's the corrected configuration:

public void ConfigureServices(IServiceCollection services)
{
    // Your existing config (APISettings, repositories, services, AutoMapper, controllers) stays unchanged here

    // Azure AD Authentication for API
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(Configuration, "AzureAd")
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddMicrosoftGraph(Configuration.GetSection("MicrosoftGraph"))
        .AddInMemoryTokenCaches();

    // Rest of your existing config (SpaStaticFiles, Session, etc.) stays unchanged here
}

Corresponding appsettings.json Setup

Make sure your appsettings.json has these single-tenant tailored sections:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "TenantId": "YOUR-TENANT-GUID-HERE",
  "ClientId": "YOUR-API-CLIENT-ID-HERE",
  "ClientSecret": "YOUR-API-CLIENT-SECRET-HERE" // Only required if using client credentials flow
},
"MicrosoftGraph": {
  "BaseUrl": "https://graph.microsoft.com/v1.0",
  "Scopes": "user.read"
}

Step 3: Resolve the "MetadataAddress or Authority Must Use HTTPS" Error

Even with RequireHttpsMetadata=false, this error pops up if:

  • Your Authority URL (auto-generated from Instance + TenantId) doesn't use HTTPS: Azure AD requires https://login.microsoftonline.com/{tenantId}—double-check you didn't omit the https:// prefix.
  • You're running in production: RequireHttpsMetadata=false is only for local development. Production environments mandate HTTPS for all authentication endpoints.

Verify your AzureAd settings to ensure the generated Authority URL is valid and HTTPS-enabled.


Step 4: Calling Microsoft Graph in Your Service

Once configured, inject GraphServiceClient into your services to interact with Microsoft Graph. For example:

public class UserService : IUserService
{
    private readonly GraphServiceClient _graphClient;

    public UserService(GraphServiceClient graphClient)
    {
        _graphClient = graphClient;
    }

    public async Task<User> GetCurrentAuthenticatedUser()
    {
        // For delegated permissions (acting as the logged-in user)
        return await _graphClient.Me.Request().GetAsync();
        
        // For client credentials flow (app-only access)
        // return await _graphClient.Users["user@yourdomain.com"].Request().GetAsync();
    }
}

Single-Tenant Tutorial Guidance

Look for Microsoft's official documentation focused on single-tenant .NET Core APIs calling Microsoft Graph using Microsoft.Identity.Web. Key points to prioritize:

  • Configuring delegated or app-only permissions for your API in Azure AD
  • Using AddMicrosoftIdentityWebApi instead of manual JwtBearer setup
  • Properly configuring token acquisition for downstream Graph calls

内容的提问来源于stack exchange,提问作者Olof84

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:37:40