Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user roles from oidc client

I am using oidc-client for my authorization in my app using angular and asp net core 3.1

How can I get the user roles from asp net thru oidc client?

like image 466
ralphytofu Avatar asked Mar 10 '26 09:03

ralphytofu


1 Answers

Identity:

public class ProfileService : IProfileService
    {
        protected UserManager<ApplicationUser> mUserManager;

        public ProfileService(UserManager<ApplicationUser> userManager)
        {
            mUserManager = userManager;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            ApplicationUser user = await mUserManager.GetUserAsync(context.Subject);

            IList<string> roles = await mUserManager.GetRolesAsync(user);

            IList<Claim> roleClaims = new List<Claim>();
            foreach (string role in roles)
            {
                roleClaims.Add(new Claim(JwtClaimTypes.Role, role));
            }

            context.IssuedClaims.AddRange(roleClaims);
        }

        public Task IsActiveAsync(IsActiveContext context)
        {
            return Task.CompletedTask;
        }
    }

Startup.cs:

...

services.AddDefaultIdentity<ApplicationUser>(options => options.User.RequireUniqueEmail = true)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddIdentityServer()
                    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

services.AddTransient<IProfileService, ProfileService>();

services.AddAuthentication()
                .AddIdentityServerJwt();

...

Angular oidc-client:

enter image description here

like image 155
Majid joghataey Avatar answered Mar 12 '26 23:03

Majid joghataey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!