使用 JwtBearer 令牌进行身份验证

This commit is contained in:
administrator committed 2024-03-16 17:11:14 +08:00
1 parent e7cbd32a39
commit 6742812bf2
15 files changed
+322 -5

No files matched your search

@@ -0,0 +1,28 @@
using HelloShop.ServiceDefaults.Constants;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System.Security.Claims;
namespace HelloShop.IdentityService;
public class CustomUserClaimsPrincipalFactory<TUser, TRole>(UserManager<TUser> userManager, RoleManager<TRole> roleManager, IOptions<IdentityOptions> options) : UserClaimsPrincipalFactory<TUser, TRole>(userManager, roleManager, options) where TUser : IdentityUser<int> where TRole : IdentityRole<int>
{
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(TUser user)
{
var claimsIdentity = await base.GenerateClaimsAsync(user).ConfigureAwait(false);
if (UserManager.SupportsUserRole)
{
var roleNames = await UserManager.GetRolesAsync(user).ConfigureAwait(false);
var roles = RoleManager.Roles.Where(r => r.Name != null && roleNames.Contains(r.Name));
foreach (var role in roles)
{
claimsIdentity.AddClaim(new Claim(CustomClaimTypes.RoleIdentifier, role.Id.ToString()));
}
}
return claimsIdentity;
}
}