1

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 Answer 1

3

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"); }); }); 
Sign up to request clarification or add additional context in comments.

3 Comments

thanks ,,I changed to what you said, now admin can access it .user role should have denied access . but user role can also access it now
@e2e can you put a breakpoint in your controller's Action somewhere and explore the User property to ensure it's got the role claim you're expecting?
Hey thanks. I figured out the problem. The problem was everytime any user credential matches I was returning all users from that function and I was giving user[0]. objects that was admin as claims . Thanks problem solved!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.