Access Denied in Asp .Net Core by Claims Authorization

Viewed 377

I have my login handler method. In that method I add claims from db to user.

public async Task<IActionResult> OnPostAsync()
{
    var result = await _signInManager.PasswordSignInAsync(LoginModel.UserName,
        LoginModel.Password, LoginModel.RememberMe, false);

    if (result.Succeeded)
    {
        var user = await _userManager.FindByNameAsync(LoginModel.UserName);
        var claims = await _userManager.GetClaimsAsync(user);
        ClaimsIdentity id = new (claims, "ApplicationCookie",
            ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(id));
        return Redirect("/");
    }

    return Page();
}

In Startup class I registered my policy like that

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

But I can't access to this PageModel when I am in admin account

[Authorize(Policy = "IsAdmin")]
public class UserPanel : PageModel
{}

Please, tell me what I am doing wrong.

1 Answers
options.AddPolicy("IsAdmin", policy => { policy.RequireClaim("Admin"); }); 

AuthorizationPolicyBuilder.RequireClaim(string) checks for the existance of a claim with the specified claim type. It will not look at claim values but just check whether there exists any claim that has a matching claim type.

Since your claim is of claim type IsAdmin with the claim value Admin, you would have to check for the IsAdmin claim instead:

// check for the claim type `IsAdmin`
options.AddPolicy("IsAdmin", policy => policy.RequireClaim("IsAdmin")); 

You can also use the other overload that also checks for claim values in addition to the claim type:

// check for the claim type `IsAdmin` with value `Admin`
options.AddPolicy("IsAdmin", policy => policy.RequireClaim("IsAdmin", "Admin")); 
Related