Why does User.IsInRole return true, but AuthorizeAttribute is not?

I am protecting an ASP.NET MVC 2 application and I have a user who is in the "Foo" role.

It's right:

User.IsInRole("Foo") 

But still, when I try to block the action of the controller, as shown below, the user is denied:

 [Authorize(Roles = "Foo")] public ActionResult PrivatePage() { return View(); } 

If IsInRole reports true, why does the Authorize attribute not allow the user?

+4
source share
3 answers

This can be caused if you keep persistent cookies for form-validated cookies. In this scenario, IsInRole can check the cookie without checking the current login.

+3
source

For future people with a similar problem - this may depend on how you actually configure your roles for the current user.

I had a similar problem when roles were pulled from a cookie with an OnActionExecuting override in the base controller. It turns out that this was done after the [Authorize] attribute, so the roles were not actually configured when the attribute checked them. The User.IsInRole call in the view was executed after OnActionExecuting , so he saw the roles in order.

So User.IsInRole returned what I expected, but the [Authorize] attribute did not.

I was able to solve this by moving the code so that the roles were in a more reasonable place that runs before the Authorize attribute - for example, in Global.asax.cs:

 protected void Application_AuthenticateRequest(Object sender, EventArgs e) { // do stuff in here } 

Or even better, in your own custom attribute - see fooobar.com/questions/101863 / ....

+1
source

They should both return true. Have you tried to use SQL Profiler to check queries executed from the database?

-1
source

Source: https://habr.com/ru/post/1337045/


All Articles