.NET 8 Blazor交互式服务器模式下如何获取OIDC访问令牌
默认配置下,AddMicrosoftIdentityWebApp不会将访问令牌存入ClaimsPrincipal,而且你需要的是针对SharePoint下游API的专用访问令牌,不是身份认证用的ID Token。以下是具体解决方案:
1. 修改Program.cs配置
首先要在认证配置中启用下游API令牌获取功能,并添加令牌缓存(必须配置,避免重复请求令牌):
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi() // 启用下游API令牌获取 .AddInMemoryTokenCaches(); // 添加内存令牌缓存(生产环境可替换为分布式缓存) // 可选:如果要直接用封装好的HttpClient调用SharePoint,注册下游API配置 builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")) .AddDownstreamWebApi("SharePointApi", builder.Configuration.GetSection("SharePointApi")) .AddInMemoryTokenCaches();
在appsettings.json中添加SharePoint API的配置(替换为你的租户和站点信息):
"SharePointApi": { "BaseUrl": "https://yourtenant.sharepoint.com/sites/yoursite", "Scopes": "https://yourtenant.sharepoint.com/AllSites.Read https://yourtenant.sharepoint.com/AllSites.Write" }
2. 获取令牌的两种方式
方式一:手动获取令牌(直接使用ITokenAcquisition)
在Razor页面或服务中注入ITokenAcquisition,调用方法获取指定Scope的令牌:
@inject ITokenAcquisition TokenAcquisition @code { private async Task CallSharePointApi() { // 替换为你需要的SharePoint权限范围 var scopes = new[] { "https://yourtenant.sharepoint.com/AllSites.Read" }; var accessToken = await TokenAcquisition.GetAccessTokenForUserAsync(scopes); // 使用令牌调用API using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await client.GetAsync("https://yourtenant.sharepoint.com/sites/yoursite/_api/web/lists"); // 处理响应逻辑 } }
方式二:使用封装的下游API服务(无需手动处理令牌)
注入IDownstreamWebApi,直接调用SharePoint API,框架会自动处理令牌获取和附加:
@inject IDownstreamWebApi DownstreamWebApi @code { private async Task CallSharePointApi() { var response = await DownstreamWebApi.CallWebApiAsync( "SharePointApi", // 对应appsettings中的配置键 options => { options.RelativePath = "_api/web/lists"; options.HttpMethod = HttpMethod.Get; }); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); // 处理返回内容 } } }
关键注意事项
- 必须在Azure AD应用注册中,给你的Blazor应用添加SharePoint的API权限,并完成管理员同意(如果是租户级权限)。
AddBearerToken是用于搭建自己的Bearer认证API服务,和获取下游API令牌无关,所以之前的尝试无效。- 令牌缓存是必须的,避免频繁向Azure AD请求令牌,影响性能。
内容的提问来源于stack exchange,提问作者M.M
相关产品推荐
相关产品推荐

