1

I have a user with the following claims: role: ["Admin","Tester"]

I want a controller method to only be accessible with the role claim value 'Admin'. For that I have added a policy like this:

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

and added the [Authorize(Policy = "Admin")] attribute on top of my controller method.

Unfortunately, when starting the application, the user does not have access.

If I remove the role Tester from his claims so that he only has Admin (role: "Admin") and it isn't an array anymore, he does have access.

As I understood, the policy should check like a "contains", but somehow that doesn't seem to work.

Am I doing something wrong?

xeraphim
  • 4,375
  • 9
  • 54
  • 102

1 Answers1

0

You might not understand it correctly. A claim has up to six parameters, and each parameter corresponds to a different function, not an array. This is source code.

public Claim(string type, string value, string valueType, string issuer, string originalIssuer, ClaimsIdentity subject);

You can add these claims one by one.

    var claims = new List<Claim>
            {
                
                new Claim("role","Tester"),
                new Claim("role","Admin"),
            };

The claims can store multiple same ClaimTypes.

enter image description here

Also, you can refer to this answer.

Karney.
  • 4,803
  • 2
  • 7
  • 11
  • 1
    yes that's how I have it, I've added multiple roles like this: `new Claim(JwtClaimTypes.Role, "Admin"), new Claim(JwtClaimTypes.Role, "Tester"),` – xeraphim Jan 12 '21 at 07:48
  • no, it didn't answer my question, I had it like this from the beginning and it doesn't work – xeraphim Jan 12 '21 at 08:43
  • Yes, but it is impossible to realize the multiple roles as you describe. Except this method, what methods can you accept to achieve? Can you describe it more clearly? – Karney. Jan 12 '21 at 09:00