Files
security/src/LiteCharmsSecurity.STS.Identity/Services/ClaimsInjectorProfileService.cs
T

56 lines
1.9 KiB
C#

using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using LiteCharmsSecurity.Admin.EntityFramework.Shared.Entities.Identity;
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace LiteCharmsSecurity.STS.Identity.Services;
public sealed class ClaimsInjectorProfileService(UserManager<UserIdentity> userManager) : IProfileService
{
public Task GetProfileDataAsync(ProfileDataRequestContext context)
=> GetProfileDataAsync(context, CancellationToken.None);
public async Task GetProfileDataAsync(ProfileDataRequestContext context, CancellationToken ct)
{
var user = await userManager.GetUserAsync(context.Subject);
if (user != null && !string.IsNullOrEmpty(user.Email))
{
var claims = new List<Claim>
{
new("email", user.Email),
new("email_verified", user.EmailConfirmed ? "true" : "false")
};
if (!string.IsNullOrEmpty(user.UserName))
claims.Add(new Claim("preferred_username", user.UserName));
var roles = await userManager.GetRolesAsync(user);
foreach (var role in roles)
claims.Add(new Claim("role", role));
var userClaims = await userManager.GetClaimsAsync(user);
foreach (var claim in userClaims)
if (!claims.Any(c => c.Type == claim.Type && c.Value == claim.Value))
claims.Add(claim);
context.IssuedClaims = claims;
}
}
public Task IsActiveAsync(IsActiveContext context)
=> IsActiveAsync(context, CancellationToken.None);
public async Task IsActiveAsync(IsActiveContext context, CancellationToken ct)
{
var user = await userManager.GetUserAsync(context.Subject);
context.IsActive = user != null;
}
}