You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.9 KiB
68 lines
1.9 KiB
3 years ago
|
using Duende.IdentityServer.Models;
|
||
|
using Duende.IdentityServer.Services;
|
||
|
using Identity.Infrastructure.Repositories;
|
||
|
using IdentityModel;
|
||
|
using System.Security.Claims;
|
||
|
using Users.Infrastructure.Entities;
|
||
|
|
||
|
namespace Identity.Realization;
|
||
|
|
||
|
public class CustomProfileService : IProfileService
|
||
|
{
|
||
|
private readonly IUserRepository UserRepository;
|
||
|
public CustomProfileService(IUserRepository userService)
|
||
|
{
|
||
|
UserRepository = userService;
|
||
|
}
|
||
|
|
||
|
async private Task<UserEntity> VerifySubAsync(ClaimsPrincipal subject)
|
||
|
{
|
||
|
subject = subject ?? throw new ArgumentNullException(nameof(subject));
|
||
|
|
||
|
var subjectId = subject.Claims.Where(x => x.Type == "sub").FirstOrDefault().Value;
|
||
|
|
||
|
if (!long.TryParse(subjectId, out long id))
|
||
|
{
|
||
|
throw new ArgumentException("主题是用户ID,但不是长类型!");
|
||
|
}
|
||
|
|
||
|
var user = await UserRepository.GetByIdAsync(id);
|
||
|
|
||
|
if (user == null)
|
||
|
{
|
||
|
throw new ArgumentException("无效的主题标识符");
|
||
|
}
|
||
|
|
||
|
return user;
|
||
|
}
|
||
|
|
||
|
async public Task GetProfileDataAsync(ProfileDataRequestContext context)
|
||
|
{
|
||
|
UserEntity user = await VerifySubAsync(context.Subject);
|
||
|
|
||
|
context.IssuedClaims = GetClaimsFromUser(user);
|
||
|
}
|
||
|
|
||
|
async public Task IsActiveAsync(IsActiveContext context)
|
||
|
{
|
||
|
UserEntity user = await VerifySubAsync(context.Subject);
|
||
|
|
||
|
context.IsActive =
|
||
|
!user.LockoutEnabled ||
|
||
|
!user.LockoutEnd.HasValue ||
|
||
|
user.LockoutEnd <= DateTime.Now;
|
||
|
}
|
||
|
|
||
|
private static List<Claim> GetClaimsFromUser(UserEntity user)
|
||
|
{
|
||
|
var claims = new List<Claim>
|
||
|
{
|
||
|
new Claim(JwtClaimTypes.Subject, user.Id.ToString()),
|
||
|
new Claim(JwtClaimTypes.NickName, user.NickName),
|
||
|
new Claim("PermissionName", "www")
|
||
|
};
|
||
|
|
||
|
return claims;
|
||
|
}
|
||
|
}
|