1
votes

I am using cookie authentication with claims identity. authentication works fine but authorization fails.

here am storing claims information if login credentials match.

 var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Name, _user[0].UserName.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Role, _user[0].UserRole));
                identity.AddClaim(new Claim(ClaimTypes.Email, _user[0].UserEmail)); 
 HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

here is the authorization setup in startup.cs configurationServices method

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

            });

and the controller

 [Authorize(Policy = "Admin")]
    public class UserController : Controller
    {
//
    }

This authorization redirects to me to access denied page although admin logs in with role. What are the problems here?

1

1 Answers

3
votes

You need to specify the claim type and what value it should have

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