簡體   English   中英

如何在客戶端獲取用戶角色?

[英]How to get user role on client side?

我正在使用 ASP.NET 核心后端開發 Angular web 應用程序。 從用於個人用戶帳戶身份驗證的內置“帶有 Angular 的 ASP.NET Core 應用程序”模板項目開始。 我的問題是在客戶端獲得經過身份驗證的用戶角色(我想在角色中處理警衛和菜單)。

現在我有 API 端點,它從后端返回用戶的角色。

當我需要了解用戶的角色時,我會調用此端點。 例如 nav-menu.component.ts 中的菜單處理

但我知道這不是最好的解決方案。 可能的代碼重復等。

還有其他解決方案嗎?

我嘗試了另一種解決方案,但效果不佳。 在登錄期間建立用戶配置文件(可以是任何)時授權服務,我應該對 append 角色進行配置。 在此處輸入圖像描述

感謝您的建議

如果您發布了代碼片段而不是圖像,那將會更有幫助。

但是,根據我在您的代碼中看到的內容,您正在訂閱另一個訂閱,這是一種不好的做法。

以下是您應該如何執行此操作:

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

如果您有權使用后端代碼,最好將 2 個端點合二為一,... 例如。 您可以像這樣在用戶名端點中結合角色端點及其在 json 中的響應

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

它將為您節省 1 個請求,而不是僅使用 2 個請求來獲取用戶名和角色。

將近一年后,我想用答案更新我的問題。

我需要創建一個實現IProfileService接口的ProfileService

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;
    }
}

向 Startup 添加了 DI 注冊

services.AddTransient<IProfileService, ProfileService>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM