asp.net-core - 覆盖 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
声明中。
解决方案
这就是我想出的使用方法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.Role
for 角色(用于在AuthorizeView
组件中使用),而不是WindowsIdentity
所需的任何类型。
我随后意识到 WindowsAuthentication 不适用于我的应用程序,我将返回自定义身份验证,该身份验证仅使用 AD 通过一对标准登录框检查其密码。
推荐阅读
- ruby-on-rails - 将 STI 与 has_many 一起使用会导致活动记录搜索子类表
- php - CakePHP 中的 $this 是什么意思?
- netlogo - 在 Netlogo 中,您可以将列表添加到一起吗?
- firebase - Flutter 上传一批图像并获取所有这些 URL 以存储在 Firestore 中
- python - ndarray 到表(从阶跃函数结果)
- python - 如何将 JSON 转换为格式化的嵌套数组?
- rust - rust 中事实上的字节类型是什么?
- php - 如何通过id从数据库中获取值
- javascript - Jquery 是 JavaScript 的替代品吗?
- angular - 将模型设置为未定义时的角度清除输入