简体   繁体   中英

How to get user role on client side?

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. Eg 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

It would've been more helpful if you have posted code snippets instead of images.

However, from what I see in your code you are subscribing inside of another subscription and that's a bad practice.

Here is how you should be doing this:

this.authorizeService
      .getUser()
      .pipe(
        // switchMap completes the previous observable and subscribe to the next one
        // the argument (user) is the data you get from the previous observable
        switchMap(user => (user ? this.authorizeService.getUserRoles(user.name) : of(null))))
      .subscribe(roles => this.roles = roles);

if you have authority to backend code it will be better to joint 2 endpoint into one,... eg. you can combine role endpoint in username endpoint and its give response in json like this

{
  username:'femix',
  role:'admin'
}

it will save you 1 request instead of using 2 request just to get username and role.

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM