Skip to content

Commit 5e3e949

Browse files
committed
Refactor GetProfileDataAsync in ProfileService class
Significant refactoring has been done to the `GetProfileDataAsync` method in the `ProfileService` class. The retrieval of the `user` object has been changed to include null checking and a different method for finding the user. The creation of the `claims` list now uses the `GetClaimsFromUser` method. Role claims are now added using the `Select` LINQ method and `AddRange`. The previous code for creating and populating the claims list and adding role claims has been replaced with this new approach.
1 parent eb02c0a commit 5e3e949

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed

Identity.API/Services/ProfileService.cs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,16 @@ public ProfileService(UserManager<ApplicationUser> userManager)
1111

1212
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
1313
{
14-
var user = await _userManager.GetUserAsync(context.Subject);
14+
var subject = context.Subject ?? throw new ArgumentNullException(nameof(context.Subject));
1515

16+
var subjectId = subject.Claims.Where(x => x.Type == "sub").FirstOrDefault()?.Value;
17+
var user = await _userManager.FindByIdAsync(subjectId)
18+
?? throw new ArgumentException("Invalid subject identifier");
1619
var roles = await _userManager.GetRolesAsync(user);
20+
var claims = GetClaimsFromUser(user).ToList();
1721

18-
var claims = new List<Claim>
19-
{
20-
new Claim(JwtClaimTypes.Subject, user.Id),
21-
new Claim(JwtClaimTypes.PreferredUserName, user.UserName),
22-
};
23-
24-
foreach (var role in roles)
25-
{
26-
claims.Add(new Claim(JwtClaimTypes.Role, role));
27-
}
22+
// Add roles to the claims
23+
claims.AddRange(roles.Select(role => new Claim(JwtClaimTypes.Role, role)));
2824

2925
context.IssuedClaims = claims;
3026
}

0 commit comments

Comments
 (0)