Role based authorization with IdentityServer4

后端 未结 3 1438
广开言路
广开言路 2020-12-13 02:25

I am trying to implement \"Role Based Authorization\" using IdentityServer4 to give access to my API based on the user roles.

For example , I want to have two roles

相关标签:
3条回答
  • 2020-12-13 02:48

    Change new Claim("role","FreeUser") to new Claim(ClaimTypes.Role, "FreeUser")

    Or create a policy like this:

    services.AddAuthorization(options =>
    {
        options.AddPolicy("FreeUser", policy => policy.RequireClaim("role", "FreeUser"));
    });
    

    and use it :

    [Authorize(Policy = "FreeUser")]
    
    0 讨论(0)
  • 2020-12-13 02:52

    Given that you have not provided config object for javascript client, I assume you have scope configured as follows.

    scope:"openid profile api1 role"
    

    I believe that the main reason for your issue is that role claim is not included in your access token.

    Add role claim to api1 scope as follows to include it in the access token.

                 new Scope
                    {
                        Name = "api1",
                        DisplayName = "API1 access",
                        Description = "My API",
                        Type = ScopeType.Resource,
                        IncludeAllClaimsForUser = true,
                        Claims = new List<ScopeClaim>
                        {
                            new ScopeClaim(ClaimTypes.Name),
                            new ScopeClaim(ClaimTypes.Role)
                        }
                    }
    

    You can read my answer here for help debug the issue. implementing roles in identity server 4 with asp.net identity

    The complete working solution is here. https://github.com/weliwita/IdentityServer4.Samples/tree/40844310

    0 讨论(0)
  • 2020-12-13 03:02

    I wrote a sample on this post

    Identity Server 4: adding claims to access token

    I have tested with Roles and claims also I can use [Authorize(Role="SuperAdmin, Admin")] in both client web app and API app.

    0 讨论(0)
提交回复
热议问题