CodeScrat
CodeScrat

Reputation: 43

Set Authorization Policy from roles stored in JWT

I have set up a Asp.Net Core 3.1 Api application which grants the tokens to users.

Users may have multiple roles. The JWT contains these roles under the claim "Role":

Role: ["Finance", "Manager"]

Authentication works, but I am trying to set up authorization, using:

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

My problem is this policy has to read the existence of "Admin" which is the part of "Role" claim. How can I make the policy that looks for an element in a claim array? I have tried RequireClaim and also tried to chain it as in policy.RequireClaim("Role").RequireClaim("Admin") to no avail.

Upvotes: 1

Views: 416

Answers (1)

CodeScrat
CodeScrat

Reputation: 43

I solved it by this overload:

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

Upvotes: 2

Related Questions