Blazor 服务器在身份验证后添加声明

时间:2021-07-30 10:57:36

标签: c# .net-core blazor-server-side claims-based-identity claims

嗨,我希望用户在登录后选择要进入的分支,并且用户可能对每个分支具有不同的角色。然后此信息将添加到用户声明中。下面是我如何实现 IClaimsTransformation TransformAsync 方法。

public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            // Clone current identity
            var clone = principal.Clone();
            var newIdentity = (ClaimsIdentity)clone.Identity;

            // Support AD and local accounts
            var nameId = principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier ||
                                                              c.Type == ClaimTypes.Name);
            if (nameId == null)
            {
                return principal;
            }

            // Get userInfo from database
            UserBranchRoleModel userInfo = await Task.Run(() => _userService.GetCurrentBranchRole(nameId.Value));
            if (userInfo?.User == null)
            {
                return principal;
            }

            List<Claim> claims = new()
            {
                new Claim(newIdentity.NameClaimType, userInfo.User.UserID),
                new Claim("BranchID", userInfo.Branch.BranchID.ToString()),
                new Claim("BranchName", userInfo.Branch.BranchName),
                new Claim(newIdentity.RoleClaimType, userInfo.Role.RoleID)
            };
            newIdentity.AddClaims(claims);
            return clone;
        }

问题是如果我不刷新页面,则声明不会更新。有没有办法在不完全刷新页面的情况下刷新声明?

这是我如何在索引页面中显示声明

@foreach (var c in @user.Claims)
{
    <div>@c.Type:  @c.Value</div>
}

这就是我更新数据库的方式

    async Task changeBranch(string UserID)
    {

        DialogOptions options = new DialogOptions() { CloseButton = false };

        DialogParameters parameters = new DialogParameters();
        parameters.Add("UserID", UserID);

        var dialog = DialogService.Show<ChooseBranch>("Select A Branch", parameters, options);
        var result = await dialog.Result;
        if (!result.Cancelled)
        {
            UserBranchRoleModel BranchRole = (UserBranchRoleModel)result.Data;
            _user.SetCurrentBranchRole(BranchRole);
            StateHasChanged();
        }
    }
}

0 个答案:

没有答案
相关问题