You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:25:16