Search code examples
asp.netasp.net-identityidentityserver4claims-based-identity

ASP.NET claim policy not authorizing


I have set up a basic TestAdmin account to use claim based Authentication in a microservice app. I have the relevant code set up as follows:

await userManager.AddClaimAsync(testAdmin, new Claim(ClaimTypes.Role, "NavInvoices"));

This shows up in the AspNetUserClaims db, so it is being created and saved. I tried these two methods to set up the Policy(I have it only checking if any ClaimTypes.Role exists right now):

services.AddAuthorization(options =>
        {
            options.AddPolicy("NavInvoices2", policy => policy.RequireClaim(ClaimTypes.Role));
        });

services.AddAuthorization(options =>
        {
            options.AddPolicy("NavInvoices", policy =>
                policy.RequireAssertion(context =>
                    context.User.HasClaim(c =>
                        (c.Type == ClaimTypes.Role))));
        });

And this is the Controller:

[Authorize(Policy = "NavInvoices")]
    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";


        return View();
    }

The problem is when I iterate over user.claims there is no role. Only things like email, name etc. In the SqlDB only my role I created exists. None of these other things that exist like name and email are in the DB. So there is a disconnect somewhere. I am using IdentityServer4's Quickstart EFandAspNetIdentity template as my base if anyone has familiarity with that.

I've googled everything I can and so far I can't find anything. I think there is two separate storages going on and the cookie is only passing one of them through to the webmvc project. Any suggestions?


Solution

  • Ensure that you are including the claims in the identity token when you are passing it to your client.

    The client configuration should have the following lines :-

      new Client
       {
         ClientId = "yourclient",
         ClientName = "Your Client",
         // left out for brevity
         AlwaysSendClientClaims = true, 
         AlwaysIncludeUserClaimsInIdToken = true
       }
    

    This should allow all of the users claims to pull through.

    You can look at this question i answered earlier for further information, and to an example on my repo :-

    IdentityServer4 custom AuthenticationHandler can't find all claims for a user