Marcel
Marcel

Reputation: 1074

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?

Upvotes: 5

Views: 2316

Answers (2)

Souhaieb Besbes
Souhaieb Besbes

Reputation: 1505

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

Upvotes: 2

CodeNotFound
CodeNotFound

Reputation: 23200

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.

Upvotes: 6

Related Questions