如何在Blazor中通过Okta获取已登录用户名
在.NET Core Blazor中获取已登录用户用户名的实现方法
1. 在Razor组件中直接获取
通过注入AuthenticationStateProvider即可获取当前登录用户信息,步骤如下:
在Blazor组件顶部注入服务:
@inject AuthenticationStateProvider AuthenticationStateProvider @using System.Security.Claims
可以通过两种方式使用用户名:
- 直接在UI中异步获取展示:
<p>当前登录用户:@(await GetCurrentUserName())</p> @code { private async Task<string> GetCurrentUserName() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity?.IsAuthenticated ?? false) { // 你的OIDC配置已设置NameClaimType为"name",直接取Identity.Name即可 return user.Identity.Name; // 如需其他Claim信息,比如邮箱:return user.FindFirst(ClaimTypes.Email)?.Value; } return "未登录"; } }
- 在组件初始化时获取并存储:
<p>当前登录用户:@currentUserName</p> @code { private string currentUserName = "未登录"; protected override async Task OnInitializedAsync() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity?.IsAuthenticated ?? false) { currentUserName = user.Identity.Name; } } }
2. 在服务或后台代码中获取
若需在非UI服务类中获取用户信息,可通过IHttpContextAccessor实现:
首先在Program.cs中注册该服务:
// 在AddServices区域添加 builder.Services.AddHttpContextAccessor();
然后在服务类中注入并使用:
using Microsoft.AspNetCore.Http; using System.Security.Claims; public class UserInfoService { private readonly IHttpContextAccessor _httpContextAccessor; public UserInfoService(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public string GetCurrentUserName() { var user = _httpContextAccessor.HttpContext?.User; if (user?.Identity?.IsAuthenticated ?? false) { return user.Identity.Name; } return "未登录"; } }
3. 关键注意事项
- 确保组件或页面添加
[Authorize]属性,限制未登录用户访问,避免空值问题:
@attribute [Authorize]
- 你的OIDC配置已设置
oidcOptions.TokenValidationParameters.NameClaimType = "name";,User.Identity.Name会自动映射Okta返回的nameClaim值,如需调整映射的Claim类型,修改该配置即可。
内容的提问来源于stack exchange,提问作者Timothy Waters
相关产品推荐
相关产品推荐

