.NET Core API调用MS Graph获取Azure AD用户信息遇阻求助
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=falsefix didn't resolve the error because there's a misconfiguration in how you're mixing authentication and Microsoft Graph integration in yourStartup.cs.
Step 1: Switch to Stable NuGet Packages
First, uninstall those preview packages and install these official, stable packages via NuGet:
Microsoft.Identity.WebMicrosoft.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
AuthorityURL (auto-generated fromInstance+TenantId) doesn't use HTTPS: Azure AD requireshttps://login.microsoftonline.com/{tenantId}—double-check you didn't omit thehttps://prefix. - You're running in production:
RequireHttpsMetadata=falseis 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
AddMicrosoftIdentityWebApiinstead of manual JwtBearer setup - Properly configuring token acquisition for downstream Graph calls
内容的提问来源于stack exchange,提问作者Olof84

