ResourceAuthorize("Read","UsersList") not working, ResourceAuthorizationManager

1.6k Views Asked by At

I am using IdentityServer3 to issue tokens and trying to use Thinktecture.IdentityModel.Owin.ResourceAuthorization.WebApi to authorize resource access of the web api.

I am using below code to Authorize an action of the controller.

[ResourceAuthorize("Read","UsersList")]

ResourceAuthorizationManager looks like below.

    public class MyAuthorizationManager : ResourceAuthorizationManager
{
    /// <summary>
    /// Verify Access Rights
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public override Task<bool> CheckAccessAsync(ResourceAuthorizationContext context)
    {
        switch (context.Resource.First().Value)
        {
            case "UsersList":
                return AuthorizeUsersList(context);
            default:
                return Nok();
        }
    }

    private Task<bool> AuthorizeUsersList(ResourceAuthorizationContext context)
    {
        switch (context.Action.First().Value)
        {
            case "Read":
                return Eval(context.Principal.HasClaim("role", "User"));
            case "Write":
                return Eval(context.Principal.HasClaim("role", "Owner"));
            default:
                return Nok();
        }
    }
}

However, when control comes to AuhtorizeUsersList, the context.Principal has no role claims. I do not store the user claims when I register a user. How can I add claims for an authenticated user on the go ?

1

There are 1 best solutions below

0
dudedev On

Maybe it will be helpful for others.

Basically, I was missing 'role' claim inside scope-claim mapping while defining the API as scope. You just have to list all the claims that you want as part of the scope, and IdentityServer will handle the rest.

On the identity server side:

new Scope
{
    Enabled = true,
    Name = "ScopeName",
    Type = ScopeType.Identity,
    Claims = new List<ScopeClaim>
    {
        new ScopeClaim("role")
    }
}