如何在Blazor Server应用中获取登录用户的城市信息?
解决Blazor Server获取已登录用户城市信息的问题
方案一:通过ID令牌直接获取城市声明(无需调用Graph API)
这种方式无需额外调用Graph接口,直接从用户身份声明中提取城市信息,效率更高。
在Azure AD应用注册中添加城市可选声明
- 登录Azure门户,找到你的应用注册,进入「令牌配置」页面
- 点击「添加可选声明」,选择「ID」令牌类型
- 在可选声明列表中找到并勾选「city」,保存配置
配置Blazor Server的OpenID Connect映射声明
修改Startup.cs/Program.cs中的认证配置,添加声明映射确保城市信息被正确解析:services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi(initialScopes) .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi")) .AddInMemoryTokenCaches() .AddOpenIdConnect(options => { // 映射city声明 options.ClaimActions.MapJsonKey("city", "city"); // 保留原有配置(如回调地址、客户端ID等) });在AuthService中读取城市声明
修改GetUserInfo方法,从认证状态中提取城市信息:public async ValueTask<UserConfiguration> GetUserInfo() { var authState = await authenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; // 获取城市声明 var city = user.FindFirst("city")?.Value; // 构建并返回用户配置 return new UserConfiguration { City = city, // 其他用户信息... }; }
方案二:通过GraphServiceClient获取城市信息(解决登录状态错误)
如果需要获取更多用户详情,可通过Graph API调用,先解决「尚未有用户登录」的错误:
修正AuthService的注入与调用逻辑
在AuthService中注入GraphServiceClient,并确保在用户认证完成后调用API:using Microsoft.AspNetCore.Components.Authorization; using Microsoft.Graph; public class AuthService : IAuthService { private readonly AuthenticationStateProvider _authenticationStateProvider; private readonly GraphServiceClient _graphServiceClient; public AuthService(AuthenticationStateProvider authenticationStateProvider, GraphServiceClient graphServiceClient) { _authenticationStateProvider = authenticationStateProvider; _graphServiceClient = graphServiceClient; } public async ValueTask<UserConfiguration> GetUserInfo() { var authState = await _authenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; // 确认用户已认证 if (!user.Identity.IsAuthenticated) { throw new UnauthorizedAccessException("用户未完成认证"); } // 调用Graph API获取用户城市信息(仅请求需要的字段,提升性能) var graphUser = await _graphServiceClient.Me .Request() .Select(u => new { u.City }) .GetAsync(); return new UserConfiguration { City = graphUser.City, // 其他用户信息... }; } }权限配置说明
- 确保应用注册添加了委派权限
User.Read(你已配置),并完成管理员同意(针对租户内用户) Directory.Read.All属于应用权限,不适用于当前的用户委派模式,无需添加
- 确保应用注册添加了委派权限
避免调用时机错误
在Blazor组件中,确保在用户认证完成后再调用AuthService.GetUserInfo,比如使用AuthorizeView包裹:<AuthorizeView> <Authorized> @{ var userConfig = await AuthService.GetUserInfo(); } <p>你的城市:@userConfig.City</p> </Authorized> <NotAuthorized> <p>请先登录</p> </NotAuthorized> </AuthorizeView>
内容的提问来源于stack exchange,提问作者Nb777
相关产品推荐
相关产品推荐

