2

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 ?

dudedev
  • 451
  • 1
  • 5
  • 19
  • My code looks like yours, but the CheckAccessAsync method is never being executed even though I have put the `ResourceAuthorize` attribute over the controller action, and I've also configured the authorization whith `app.UseResourceAuthorization(MyAuthorizationManager)`. Do you know if there's any other thing I need to do also to get this working? – Ulysses Alves Mar 21 '17 at 18:52
  • I guess, It should be `app.UseResourceAuthorization(new MyAuthorizationManager())` – dudedev Mar 23 '17 at 12:31
  • To add claims on the go, override GetClaimsForUserAsync method of class AbstractIdentityUserService (Axoom.Core.IdentityServer.Services) and add claims there. – dudedev Mar 23 '17 at 12:35
  • I've found the reason. It was because I was using package `Thinktecture.IdentityModel.Owin.ResourceAuthorization.*Mvc*` instead of `Thinktecture.IdentityModel.Owin.ResourceAuthorization.*WebApi*`. Now everything is working nice, thanks. – Ulysses Alves Mar 23 '17 at 16:44

1 Answers1

1

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")
    }
}
Rahatur
  • 3,147
  • 3
  • 33
  • 49
dudedev
  • 451
  • 1
  • 5
  • 19