Authorization based on multiple scopes in C# web API ( scopes based authorization ) using policies

2.7k views Asked by At

I am posting this to share information to Authorization in C# WEB API using multiple scopes.

After posting this user-defined I got a simple answer from https://stackoverflow.com/users/4830196/ryan-wilson

Thank you Ryan-Wilson for commenting your answer instead of just ignoring question.

i.e

options.AddPolicy("ReadPolicy", policy => {
       policy.RequireClaim("scope","scope1","scope2");
});

Authorizing based on a single scope I found reference from https://docs.duendesoftware.com/identityserver/v5/apis/aspnetcore/authorization/

i.e in :

services.AddAuthorization(options =>
    {
        options.AddPolicy("read_access", policy =>
            policy.RequirementClaim("scope", "item1.read");
    });

and utilizing it at the end point:

public class DataController : ControllerBase
{
    [Authorize(Policy="read_access")]
    public async Task<IActionResult> Get()
    {
        return logic here
    }
}

The above only works for single scope i.e item1.read. If we want a logic to make the end point accessible with either of multiple scopes if have written following logic.

options.AddPolicy("ReadPolicy", policy => {
       policy.RequireAssertion(context => {
           return context.User.HasClaim(c =>
               (c.Type == "scope" &&
                  (c.Value.Contains("item.read") ||
                   c.Value.Contains("complete.read")   
                  )
             ));
         });
});

Here the scope item1.read means providing scope for only 1st item and scope complete.read means full access.

Hope this might helpful for any of us. Please hit like if this is understandable and useful. If not please share comment on how to improve my skills.

Thank you,

Naveen Devi.

0

There are 0 answers