在CustomAuthenticationStateProvider中获取系统用户名的方法
解决方案
1. 访问原GetAuthenticationStateAsync方法
你的自定义AuthenticationStateProvider应当继承Blazor Server内置的ServerAuthenticationStateProvider,在重写GetAuthenticationStateAsync方法时,直接通过base.GetAuthenticationStateAsync()即可调用原生实现逻辑。
2. 实现自动登录(系统用户名验证)
结合你的需求,可在重写的方法中完成系统用户名获取→用户表权限验证→构造认证状态的完整流程,具体步骤如下:
步骤1:获取系统用户名
根据部署场景选择对应方式:
- 若采用Windows集成认证,直接通过
WindowsIdentity.GetCurrent().Name获取当前系统用户名; - 若基于请求上下文获取用户,需注入
IHttpContextAccessor,通过_httpContextAccessor.HttpContext?.User.Identity?.Name提取用户名。
步骤2:验证用户权限
调用你的用户表查询逻辑,确认该用户名是否存在且处于可登录状态(比如账号激活、权限匹配等)。
步骤3:构造并返回认证状态
验证通过则创建包含用户信息的ClaimsPrincipal,包装为AuthenticationState返回;验证失败则回退到原生方法的默认逻辑。
代码示例
public class CustomAuthStateProvider : ServerAuthenticationStateProvider { private readonly IUserRepository _userRepository; private readonly IHttpContextAccessor _httpContextAccessor; public CustomAuthStateProvider(IUserRepository userRepository, IHttpContextAccessor httpContextAccessor) { _userRepository = userRepository; _httpContextAccessor = httpContextAccessor; } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { // 获取系统/请求关联的用户名 var userName = _httpContextAccessor.HttpContext?.User.Identity?.Name ?? WindowsIdentity.GetCurrent().Name; if (!string.IsNullOrEmpty(userName)) { // 查询用户表验证权限 var user = await _userRepository.GetUserByUserNameAsync(userName); if (user != null && user.IsActive) { // 构造带用户信息的ClaimsPrincipal var claims = new List<Claim> { new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.Role, user.Role) }; var identity = new ClaimsIdentity(claims, "CustomAutoAuth"); var principal = new ClaimsPrincipal(identity); return new AuthenticationState(principal); } } // 自动验证失败,执行原生方法逻辑 return await base.GetAuthenticationStateAsync(); } }
注意事项
- 需在
Program.cs中注册IHttpContextAccessor:builder.Services.AddHttpContextAccessor(); - 若使用Windows集成认证,需在项目中启用Windows身份验证并关闭匿名认证(可通过项目属性或
launchSettings.json配置) - 自定义认证类型(示例中的
CustomAutoAuth)需与你的授权逻辑匹配,确保权限验证能正确识别
内容的提问来源于stack exchange,提问作者Rob Marsh
相关产品推荐
相关产品推荐

