ClaimType.GivenName 不返回我的名字



我正在开发.NET Core 2.2从Azure AD进行身份验证的应用。我想在Razor Web应用中的_loginpartial.cshtml中获取用户的名字。我能够获取用户的姓氏和电子邮件,但不能获得名字。有什么可以得到的吗?

这就是我在登录部分视图中所拥有的:

Claim nameClaim = User.Claims.FirstOrDefault<Claim>(claim => string.Compare(claim.Type, "name", StringComparison.Ordinal) == 0);
    string userName = (nameClaim != null) && !string.IsNullOrEmpty(nameClaim.Value) ? nameClaim.Value : ((User != null) && (User.Identity != null) ? User.Identity.Name : string.Empty);

我也尝试过:

@User.FindFirst(System.Security.Claims.ClaimTypes.GivenName).Value

给定名称返回电子邮件与名称和电子邮件属性相同!

通过在ASP.NET中扩展身份模型来获取名字的理想方式是什么?

对于身份,内置IdentityUser中没有FirstName,您需要实现自己的用户,例如:

public class ApplicationUser:IdentityUser
{
    public string FirstName { get; set; }
}

然后,实现UserClaimsPrincipalFactory<ApplicationUser>

public class CustomClaimsIdentityFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
    public CustomClaimsIdentityFactory(UserManager<ApplicationUser> userManager
        , IOptions<IdentityOptions> optionsAccessor) 
        : base(userManager, optionsAccessor)
    {
    }
    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);
        //custom claims
        ((ClaimsIdentity)principal.Identity).AddClaims(new[] {
          new Claim("FirstName", user.FirstName)
          });
        return principal;
    }
}

然后,您可以通过@User.Claims.FirstOrDefault(c => c.Type == "FirstName")?.Value检查FirstName,例如

@using Microsoft.AspNetCore.Identity
@using TestIdentity.Data
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
<ul class="navbar-nav">
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a  class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Claims.FirstOrDefault(c => c.Type == "FirstName")?.Value!</a>
    </li>
    <li class="nav-item">
        <form  class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
            <button  type="submit" class="nav-link btn btn-link text-dark">Logout</button>
        </form>
    </li>
}
else
{
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
    </li>
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
    </li>
}
</ul>

相关内容

  • 没有找到相关文章