Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

c# - Access Denied in Asp .Net Core by Claims Authorization

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.

question from:https://stackoverflow.com/questions/65873722/access-denied-in-asp-net-core-by-claims-authorization

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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")); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...