Issue
I’m working on Angular web application with ASP.NET Core back end. Started with built in “ASP.NET Core application with Angular” template project for Individual User Accounts authentication. My problem is to get authenticated user’s role on client side (i want to handle guards and menus within the roles).
Now i have API endpoint which give back the user’s role from back end.
This endpoint i call when i need to know about user’s role. E.g. menu handling in
nav-menu.component.ts
But i know this is not the best solution. Possible code duplication etc.
There is any other solution?
I tried an another solution but dont works good.
In authorize service when user profile (which is any) is built up during signing in i should append roles to profile.
thanks for any advice
Solution
After almost a year, I would like to update my question with answer.
I needed to create a ProfileService
which implements IProfileService
interface
public class ProfileService : IProfileService
{
protected UserManager<ApplicationUser> UserManager;
public ProfileService(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
ApplicationUser user = await UserManager.GetUserAsync(context.Subject);
IList<string> roles = await UserManager.GetRolesAsync(user);
var claims = new List<Claim> {
// here you can include other properties such as id, email, address, etc. as part of the jwt claim types
new Claim(JwtClaimTypes.Email, user.Email),
new Claim(JwtClaimTypes.Name, $"{user.Firstname} {user.Lastname}")
};
foreach (string role in roles)
{
// include the roles
claims.Add(new Claim(JwtClaimTypes.Role, role));
}
context.IssuedClaims.AddRange(claims);
}
public Task IsActiveAsync(IsActiveContext context)
{
return Task.CompletedTask;
}
}
Added DI registration to Startup
services.AddTransient<IProfileService, ProfileService>();