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

Blazor Server中IClaimsTransformation调用及角色缓存行为疑问

IClaimsTransformation在Blazor Server中仅启动时调用,角色变更无法实时生效的问题

我正在用.NET Core开发小型Blazor Server应用,计划将现有基于.NET WebForms的大型内部应用迁移至该框架。我们采用Windows身份验证(仅域内用户可访问)结合数据库UserRoles表存储角色的方案。

已完成一个采用Windows身份验证的Blazor Server应用,通过IClaimsTransformation类从数据库获取用户角色并添加为声明,目前授权功能可正常使用。原以为每次应用执行授权规则时,都会调用IClaimsTransformation进而触发数据库查询获取角色,但调试时发现TransformAsync方法仅在应用启动时被多次调用(每次都会查询数据库),之后便不再执行。带有授权规则的页面仍能正常生效,推测角色被默认缓存(我未手动配置缓存),这导致用户在使用应用期间角色变更时,应用中的声明无法更新,仅能通过重启应用使新角色生效。我想确认该行为是否符合预期,或是我的配置存在遗漏。

ClaimsTransformer实现代码

public class ClaimsTransformer : IClaimsTransformation
{
    private readonly UserProfileService _userProfileService;
   
    public ClaimsTransformer(UserProfileService userProfileService) 
    {
        _userProfileService = userProfileService;
    }

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        // 用户未通过身份验证,直接返回
        if (principal.Identity?.IsAuthenticated is false)
        {
            return principal;
        }

        ClaimsIdentity claimsIdentity = new ClaimsIdentity(); 

        // 调用UserProfileService中的方法,获取指定用户名的角色列表
        List<Role> roleList = (await _userProfileService.GetRolesForUserNameAsync(principal.Identity.Name)).ToList();

        foreach (Role r in roleList) {
            if (!principal.HasClaim(claim => claim.Type == r.RoleName))
            {
                claimsIdentity.AddClaim(new Claim(claimsIdentity.RoleClaimType, r.RoleName));
            }                
        }
        principal.AddIdentity(claimsIdentity);
        return principal;
    }
}

Program.cs配置代码

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) 
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    // 默认情况下,所有传入请求将根据默认策略进行授权
    options.FallbackPolicy = options.DefaultPolicy;    
}); 

builder.Services.AddTransient<IClaimsTransformation, ClaimsTransformer>();

页面授权视图代码

<AuthorizeView Roles="Admin">
    <Authorized>
        <p>您是管理员</p>
    </Authorized>
    <NotAuthorized>
        <p>您不是管理员</p>
    </NotAuthorized>    
</AuthorizeView>

内容的提问来源于stack exchange,提问作者gib_stu01

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:33:26