get more claims

This commit is contained in:
Paul Schneider
2025-02-09 16:57:10 +00:00
parent 44dfb0021a
commit d1cadd9df8
7 changed files with 140 additions and 174 deletions

View File

@ -2,6 +2,7 @@ using System.Security.Claims;
using IdentityModel;
using IdentityServer8.Models;
using IdentityServer8.Services;
using IdentityServer8.Stores;
using Microsoft.AspNetCore.Identity;
using Yavsc.Models;
@ -10,38 +11,65 @@ namespace Yavsc.Services
public class ProfileService : IProfileService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public ProfileService(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
_roleManager = roleManager;
}
public async Task<List<Claim>> GetClaimsFromUserAsync(ApplicationUser user)
public async Task<List<Claim>> GetClaimsFromUserAsync(
ProfileDataRequestContext context,
ApplicationUser user)
{
var allowedScopes = context.Client.AllowedScopes
.Where(s => s != JwtClaimTypes.Subject)
.ToList();
if (allowedScopes.Contains("profile"))
{
allowedScopes.Remove("profile");
allowedScopes.Add(JwtClaimTypes.Name);
allowedScopes.Add(JwtClaimTypes.FamilyName);
allowedScopes.Add(JwtClaimTypes.Email);
allowedScopes.Add(JwtClaimTypes.PreferredUserName);
allowedScopes.Add("http://schemas.microsoft.com/ws/2008/06/identity/claims/role");
}
var claims = new List<Claim> {
new Claim(JwtClaimTypes.Subject,user.Id.ToString()),
new Claim(JwtClaimTypes.PreferredUserName,user.UserName)
};
var role = await _userManager.GetRolesAsync(user);
role.ToList().ForEach(f =>
foreach (var subClaim in context.Subject.Claims)
{
claims.Add(new Claim(JwtClaimTypes.Role, f));
});
if (allowedScopes.Contains(subClaim.Type))
claims.Add(subClaim);
}
AddClaims(allowedScopes, claims, JwtClaimTypes.Email, user.Email);
AddClaims(allowedScopes, claims, JwtClaimTypes.PreferredUserName, user.FullName);
foreach (var scope in context.Client.AllowedScopes)
{
claims.Add(new Claim("scope", scope));
}
return claims;
}
private static void AddClaims(List<string> allowedScopes, List<Claim> claims,
string claimType, string claimValue
)
{
if (allowedScopes.Contains(claimType))
if (!claims.Any(c => c.Type == claimType))
claims.Add(new Claim(claimType, claimValue));
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var subjectId = context.Subject.Claims.FirstOrDefault(c => c.Type == "sub").Value;
var user = await _userManager.FindByIdAsync(subjectId);
context.IssuedClaims = await GetClaimsFromUserAsync(user);
context.IssuedClaims = await GetClaimsFromUserAsync(context, user);
}