首页 > 解决方案 > 覆盖 ASP.NET Core Windows 身份验证标识

问题描述

我希望对 Blazor Server 应用程序使用 Windows 身份验证,但在默认身份名称方面遇到了一个小问题。即当你使用

<AuthorizeView>
   Hi @context.User.Identity.Name
</AuthorizeView>

我返回了“Hi DOMAIN\A123456”,这可能是 AD 对象名称,但不是用户所说的名称。在调试过程中,我还注意到 Identity 已经撤回了我所有的 AD 组,但没有像 Given Name 这样的东西。

如何覆盖/修改/更改处理以“修复”此问题,理想情况下在Name声明中放置一个正确的名称并将 id 移动到NameIdentifier声明中。

标签: asp.net-coreauthenticationactive-directoryblazorwindows-identity

解决方案


这就是我想出的使用方法IClaimsTransformation,但不确定它是否是正确的方法,尤其是考虑到开箱即用的 Blazor 项目,这个东西被调用了 7 次!如果我添加了任何数据库类型逻辑来获取角色或名称,那么这就是坦克性能......

public class RoleClaimsTransformer : IClaimsTransformation
{
    private readonly ILogger<RoleClaimsTransformer> _logger;

    public RoleClaimsTransformer(ILogger<RoleClaimsTransformer> logger)
    {
        _logger = logger;
    }

    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        _logger.LogDebug($"Role Transform for {principal.Identity.Name} Auth: {principal.Identity.IsAuthenticated}");

        //get the original name claim
        var ci = (ClaimsIdentity)principal.Identity;
        Claim nameClaim = principal.FindFirst(ci.NameClaimType);

        //create a new principal
        ClaimsPrincipal newCP = new ClaimsPrincipal();
        //and a new identity, using the original authtype (just in case it matters down the line)
        var newId = new GenericIdentity("Joe Bloggs", principal.Identity.AuthenticationType);
        //add the original name as a NameId
        newId.AddClaim(new Claim(ClaimTypes.NameIdentifier, nameClaim.Value));
        //add roles etc
        newId.AddClaim(new Claim(ClaimTypes.Role, "admin"));

        newCP.AddIdentity(newId);

        return Task.FromResult(newCP);
    }
}

希望它相当清楚我所做的事情,但基本上忽略内置 Windows Auth 的主体并创建自己的。另请注意,GenericIdentity确实需要一个ClaimTypes.Rolefor 角色(用于在AuthorizeView组件中使用),而不是WindowsIdentity所需的任何类型。

我随后意识到 WindowsAuthentication 不适用于我的应用程序,我将返回自定义身份验证,该身份验证仅使用 AD 通过一对标准登录框检查其密码。


推荐阅读