簡體   English   中英

Identity Server 4 向用戶添加自定義聲明

[英]Identity Server 4 add custom claims to User

我已經設置了 Identity Server 4(不久前,所以我忘記了很多事情)並且我正在嘗試對當前登錄的用戶設置聲明。 當我登錄並使用過濾器查看他們有什么聲明時,我可以看到:

在此處輸入圖像描述

您可以從此圖像中看到我的范圍、聲明和角色已添加到用戶中,這很好。 但是這些聲明有一種我認為是錯誤的角色 我想將其更改為聲明

在此處輸入圖像描述

我已經在我的應用程序中搜索了ClaimTypes.Rolerole ,但找不到我在哪里設置的。 這是可以輕松完成的事情嗎?

我設法解決了這個問題; 所以基本上我已經設置了角色。 我只是不明白我過去是怎么做到的。 要做的主要事情是設置我這樣做的ApiResource

new ApiResource(IdentityConstants.ApiResources.IdentityServer, "Identity Server", new[] {JwtClaimTypes.Role, IdentityConstants.ClaimTypes.Permission})

我的常量 class 只有幾個 static 字符串設置如下:

public static class SituIdentityConstants
{
    public static class ApiResources
    {
        public const string Sxp = "sxp";
        public const string IdentityServer = "identity-server";
    }

    public static class ClaimTypes
    {
        public const string Permission = "permission";
    }
}

一旦完成; 我更新了我的種子並包括了這個:

private static void CreateApiResources(ConfigurationDbContext context)
{
    var scopes = ListApiScopes();
    var resources = ListApiResources();

    foreach (var scope in scopes)
        if (!context.ApiScopes.Any(m => m.Name.Equals(scope.Name)))
            context.ApiScopes.Add(scope.ToEntity());

    foreach (var resource in resources)
    {
        if (context.ApiResources.Any(m => m.Name.Equals(resource.Name))) continue;

        var entity = resource.ToEntity();
        entity.Scopes = scopes.Select(m => new ApiResourceScope
        {
            Scope = m.Name
        }).ToList();
        context.Add(entity);
    }

    context.SaveChanges();
}

它創建了所有 API 資源、范圍和任何 ApiResourceClaims(這是在IProfileService中填充RequestedClaimTypes的內容。

順便說一句,作為參考,這是我的ProfileService

public class ProfileService: IProfileService
{
    private readonly IMediator _mediator;
    private readonly UserManager<User> _userManager;
    private readonly RoleManager<Role> _roleManager;
    
    public ProfileService(IMediator mediator, UserManager<User> userManager, RoleManager<Role> roleManager)
    {
        _mediator = mediator;
        _userManager = userManager;
        _roleManager = roleManager;
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var user = await _userManager.FindByIdAsync(context.Subject.GetSubjectId());
        var rolesAttempt = await _mediator.Send(new ListRoles());
        if (rolesAttempt.Failure) return;

        var roles = rolesAttempt.Result;
        var issuedClaims = new List<System.Security.Claims.Claim>();
        
        foreach (var role in roles)
        {
            if (!user.Roles.Any(m => m.RoleId.Equals(role.Id))) continue;

            issuedClaims.Add(new System.Security.Claims.Claim(JwtClaimTypes.Role, role.Name));

            var roleClaims = await _roleManager.GetClaimsAsync(new Role {Id = role.Id});
            issuedClaims.AddRange(roleClaims.Where(m => context.RequestedClaimTypes.Any(x => x.Equals(m.Type))));
        }
        
        context.IssuedClaims = issuedClaims;
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        var sub = context.Subject.GetSubjectId();
        var user = await _userManager.FindByIdAsync(sub);
        var active = (user != null && (!user.LockoutEnabled || user.LockoutEnd == null)) ||
                     (user != null && user.LockoutEnabled && user.LockoutEnd != null &&
                      DateTime.UtcNow > user.LockoutEnd);

        context.IsActive = active;
    }
}

我實際上發現這是一個痛苦的設置。 我嘗試了文檔所述的方式:

services.AddIdentityServer()
    .AddDeveloperSigningCredential()
    // Stores clients and resources
    .AddConfigurationStore(options => options.ConfigureDbContext = ConfigureDbContext)
    // Stores tokens, consents, codes, etc
    .AddOperationalStore(options => options.ConfigureDbContext = ConfigureDbContext)
    .AddProfileService<ProfileService>()
    .AddAspNetIdentity<User>();

但這對我不起作用; 所以我這樣做了:

services.AddIdentityServer()
    .AddDeveloperSigningCredential()
    // Stores clients and resources
    .AddConfigurationStore(options => options.ConfigureDbContext = ConfigureDbContext)
    // Stores tokens, consents, codes, etc
    .AddOperationalStore(options => options.ConfigureDbContext = ConfigureDbContext)
    .AddAspNetIdentity<User>();

services.AddScoped(typeof(IProfileService), typeof(ProfileService));

這就是我需要為 Identity Server 做的所有事情, RequestedClaimTypes現在填充了“角色”和“權限”。 我唯一做的另一件事是,當我創建 RoleClaim 時,我將聲明類型設置為“permission”並且它可以工作:

{
    "nbf": 1611600995,
    "exp": 1611604595,
    "iss": "https://localhost:44362",
    "aud": [
        "sxp",
        "identity-server"
    ],
    "client_id": "client",
    "sub": "949cc454-d7c9-45db-9eae-59e72d3025c1",
    "auth_time": 1611600983,
    "idp": "local",
    "role": "User Manager",
    "permission": [
        "users:write",
        "user:read"
    ],
    "jti": "39C9F31958972704730DA65A8FCDAAEE",
    "iat": 1611600995,
    "scope": [
    "identity:read",
    "identity:write",
        "sxp:read",
        "sxp:write"
    ],
    "amr": [
    "pwd"
    ]
}

噪音。

暫無
暫無

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

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