为身份用户自定义实施 get/set 方法 属性

Implement get/set methods for Identity User custom property

我正在使用 Identity 并使用三个自定义属性扩展了基本 IdentityUser。使用 .netCore 3.1.1 和身份 4

namespace FleetLogix.Intranet.Identity
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser<int>
    {
        [MaxLength(50)]
        [PersonalData]
        public string FirstName { get; set; }

        [MaxLength(50)]
        [PersonalData]
        public string LastName { get; set; }

        [MaxLength(5)]
        public string OrgCode { get; set; }

        public ApplicationUser() : base()
        {

        }


    }
}

这些是在 [AspNetUsers] table 中愉快地创建的。已创建 4 个初始用户,并填充了所有其他属性。

我还创建了一些扩展,让我可以获取这些属性的值。 FirstName -> GivenName,LastName -> Surname 和 OrgCode 是 CustomClaimTypes.OrgCode

namespace FleetLogix.Intranet.Identity
{
    /// <summary>
    /// Extends the <see cref="System.Security.Principal.IIdentity" /> object to add accessors for our custom properties.
    /// </summary>
    public static class IdentityExtensions
    {
        /// <summary>
        /// Gets the value of the custom user property FirstName
        /// </summary>
        /// <example>
        /// User.Identity.GetFirstName()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of LastName or an empty string</returns>
        public static string GetFirstName(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(ClaimTypes.GivenName);

            return claim?.Value ?? string.Empty;
        }

        /// <summary>
        /// Gets the value of the custom user property LastName
        /// </summary>
        /// <example>
        /// User.Identity.GetLastName()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of LastName or an empty string</returns>
        public static string GetLastName(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(ClaimTypes.Surname);

            return claim?.Value ?? string.Empty;
        }


        /// <summary>
        /// Gets the value of the custom user property OrgCode
        /// </summary>
        /// <example>
        /// User.Identity.GetOrgCode()
        /// </example>
        /// <param name="identity">Usually the Identity of the current logged in User</param>
        /// <returns><see langword="string"/> containing value of OrgCode or an empty string</returns>
        public static string GetOrgCode(this IIdentity identity)
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
            Claim claim = claimsIdentity?.FindFirst(CustomClaimTypes.OrgCode);

            return claim?.Value ?? string.Empty;
        }
    }
}

我正在建立一个新站点并想修改 _LoginPartial.cshtml。我想用登录的名字

替换登录用户名(电子邮件地址)的显示
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
    <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a> 
    </li>
   ...
}

至此

@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
    <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.GetFirstName()!</a> 
    </li>
   ...
}

但是,这会导致文本为空。 为什么这里是空白的?

点击进入 Account/Manage/Index 页面后,我看到了一个用于修改用户详细信息的表单。我修改了 InputModel 以包含两个自定义属性(FirstName、LastName)。 LoadAsync 任务已修改为加载值(使用扩展方法)并将它们添加到 `InputModel

private async Task LoadAsync(ApplicationUser user)
{

    var userName = await _userManager.GetUserNameAsync(user);
    var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
    var firstName =  user.FirstName;
    var lastName = user.LastName;
    var orgCode = user.OrgCode;


    Username = userName;

    OrgCode = orgCode;

    Input = new InputModel
    {
        PhoneNumber = phoneNumber,
        FirstName = firstName,
        LastName = lastName

    };
}

为什么自定义属性在此页可见,而在上一页不可见?

Account/Manage/Index中还有更新方法OnPostAsync()

public async Task<IActionResult> OnPostAsync()
{
   var user = await _userManager.GetUserAsync(User);
   if (user == null)
   {
       return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
   }

   if (!ModelState.IsValid)
   {
       await LoadAsync(user);
       return Page();
   }

   var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
   if (Input.PhoneNumber != phoneNumber)
   {
       var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
       if (!setPhoneResult.Succeeded)
       {
           var userId = await _userManager.GetUserIdAsync(user);
           throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
       }
   }

   var firstName = user.FirstName; //.GetPhoneNumberAsync(user);
   if (Input.FirstName != firstName)
   {
       //var setFirstNameResult = await _userManager.SetFirstNameAsync(user, Input.FirstName);
       user.FirstName = Input.FirstName;
       //if (!setFirstNameResult.Succeeded)
       //{
       //    var userId = await _userManager.GetUserIdAsync(user);
       //    throw new InvalidOperationException($"Unexpected error occurred setting First Name for user with ID '{userId}'.");
       //}
   }


   var lastName = user.LastName;
   if (Input.LastName != lastName)
   {
       //var setLastNameResult = await _userManager.SetLastNameAsync(user, Input.LastName);
       user.LastName = Input.LastName;
       //if (!setLastNameResult.Succeeded)
       //{
       //    var userId = await _userManager.GetUserIdAsync(user);
       //    throw new InvalidOperationException($"Unexpected error occurred setting Last Name for user with ID '{userId}'.");
       //}
   }

   await _signInManager.RefreshSignInAsync(user);
   StatusMessage = "Your profile has been updated";
   return RedirectToPage();
}

没有像 SetPhoneNumberAsync() 这样的 Set 方法,我尝试使用 属性 setter。这没有用。 如何更新身份用户自定义 属性 值?

我只想能够使用自定义用户属性。我需要在他们登录后立即提供 FirstName & OrgCode 属性,但目前情况并非如此。当前的扩展方法并不总是有效。

此外,我需要能够编辑这些属性,以防它们出错或更改要求。

您需要创建身份范围,只需创建您的身份并添加范围

services.AddScoped<IUserIdentity, UserIdentity>();

您需要实施 middleware 以映射身份中的所有属性。 添加到启动:

app.UseMiddleware<UserIdentityAccessor>();

实施:

    public class UserIdentityAccessor
    {
        private readonly RequestDelegate _next;

        public UserIdentityAccessor(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, IUserIdentity userIdentity)
        {
            var user = (ClaimsIdentity) context.User.Identity;

            if (user.IsAuthenticated)
            {
                var first = user.FindFirst(ClaimsName.FirstName).Value; \ get info from claims
                userIdentity.FirstName = first;                         \ and add to identity
            }
            else
            {
                userIdentity.FirstName = null;
            }

            await _next(context);
        }
    }

现在您可以随时随地获得身份