Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an exception on AuthorizeAttribute

I have a controller with many actions. All should be accessible to certain users only except one action:

[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
        return View(...);
    }

    ...
}

Even [Authorize (Roles = null)] doesn't work. The method attribute will be ignored! How could I get the exception for just one action? Like AllowAnonymous allows it but visible to logged in users?

like image 781
Marcel Avatar asked Feb 28 '16 16:02

Marcel


2 Answers

You can use OverrideAuthorization attribute like I do in the code below :

[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{

    [OverrideAuthorization]
    [Authorize()]
    public ActionResult Index()
    {
        return View(...);
    }

    ...
}

With [OverrideAuthorization] which came with ASP.Net MVC5 you tell your Index action to override/ignore the authorization rules defined at the controller level.

By doing this, all your actions defined in SecretsController are visible only to Admin role except Index action which will be visible only to authenticated user even if they are not in Admin role.

like image 105
CodeNotFound Avatar answered Oct 11 '22 12:10

CodeNotFound


use the attribute AllowAnonymous

[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{
    [AllowAnonymous]
    public ActionResult Index()
    {
        return View(...);
    }

    ...
}

Edit Since the question was edited right after my answer to precisely mention not wanting the anonymous option

Like AllowAnonymous allows it but visible to logged in users?

The best answer is now CodeNotFound's answer

like image 22
Souhaieb Besbes Avatar answered Oct 11 '22 11:10

Souhaieb Besbes