C# Web API中使用MS Graph SDK访问Microsoft Graph自动授权问题
C# Web API 自动配置MS Graph SDK授权方案
1. 校验appsettings.json配置
确保配置项完整且正确,尤其注意应用权限模式下的Scope设置:
"AzureAd": { "Instance": "https://login.microsoftonline.com/", "TenantId": "你的租户ID", "ClientId": "Azure AD应用客户端ID", "ClientSecret": "Azure AD应用客户端密钥" }, "GraphApi": { "Scopes": "https://graph.microsoft.com/.default" }
注:
https://graph.microsoft.com/.default表示使用Azure AD中已配置的所有应用权限,需提前在Azure Portal给应用添加对应Graph应用权限并完成管理员同意。
2. Program.cs中正确注册服务
安装必要NuGet包:Microsoft.Identity.Web、Microsoft.Identity.Web.MicrosoftGraph,然后在Program.cs中完成自动授权配置:
var builder = WebApplication.CreateBuilder(args); // 注册Azure AD身份验证及下游API调用能力 builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi() // 自动配置GraphServiceClient及TokenCredential .AddMicrosoftGraph(builder.Configuration.GetSection("GraphApi")) .AddInMemoryTokenCaches(); builder.Services.AddControllers(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
3. 控制器中直接使用GraphServiceClient
无需手动处理Token,直接注入后调用接口:
[ApiController] [Route("api/[controller]")] public class GraphController : ControllerBase { private readonly GraphServiceClient _graphClient; public GraphController(GraphServiceClient graphClient) { _graphClient = graphClient; } [HttpGet("users")] public async Task<IActionResult> GetAllUsers() { var userList = await _graphClient.Users.Request().GetAsync(); return Ok(userList); } }
常见排查点
- 确认Azure AD应用配置的是应用权限而非委托权限,委托权限依赖用户上下文,不适合无用户交互的Web API场景
- 检查NuGet包版本,避免因版本兼容问题导致自动授权失效
- 验证appsettings.json中的配置键名是否与代码对应,比如
TenantId、ClientSecret不能拼写错误 - 如果是用户上下文场景(Web API接收用户令牌后调用Graph),需将
GraphApi:Scopes替换为具体的委托权限范围,同时确保前端传递的用户令牌包含对应权限
内容的提问来源于stack exchange,提问作者Krzysztof Klekot
相关产品推荐
相关产品推荐

