是否可以在 MVC 控制器中禁用对一个操作的授权?

我在控制器上有一个授权属性,但是我想在一个操作上关闭它。 我创建了自己的授权过滤器,并将“匿名”添加到角色列表中。在筛选器中,如果 Anonymous 出现在角色列表中,则返回 true。

然而,它似乎并没有通过登录页面,就好像控制器授权抢占了其他任何东西一样。

58543 次浏览

Do not add AuthorizationAttribute on your action method where ever you do not required for example.

My custom attribute

public class AuthorizationFilterAttribute : AuthorizeAttribute
{
// Some code...
}

My controller

public class UserController : BaseController, IDisposable
{
[AuthorizationFilterAttribute]
public ActionResult UserList()
{
// Authorize attribute will call when this action is executed
}


public ActionResult AddUser()
{
// Authorize attribute will not call when this action is executed
}
}

I hope you got my point what I am trying to say you.

============================ Updated Answer ================================

Create one more attribute like below.

public sealed class AnonymousAttribute : Attribute { }

Please put below code on your OnAuthorization method.

public override void OnAuthorization(AuthorizationContext filterContext)
{
bool checkForAuthorization =
filterContext.ActionDescriptor.IsDefined(typeof(AnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AnonymousAttribute), true);


if (!skipAuthorization)
{
base.OnAuthorization(filterContext);
}
}

You can create your own version of the attribute.

There is a very similar question and there is a pretty good answer how to implement your own attribute that handles this situation.

Override Authorize Attribute in ASP.NET MVC

Btw. you could also create your controller that would have authorization by default.

Base

[Authorize]
public abstract class SecureControllerBase : Controller
{
}

Usage

public class MyController : SecureControllerBase
{
}

Simply add the attribute to the Actions you want to filter, and not on the controller class. By not decorating actions, they will not be filtered, provided the controller or one of its base controllers hasn't got the attribute.

You can add [Authorize] To the controller class, and then add [AllowAnonymous] to the single action you don't want to be authorized. Example:

[Authorize]
public class AccountController : Controller
{
public ActionResult Profile()
{
return View();
}


[AllowAnonymous]
public ActionResult Login()
{
return View();
}
}

I just did a solution using Azure ACS as the federated Identity Provider and the accepted answer didn't work for me. For those who are struggling, my solution was to bypass the security altogether for the required controller/views.

Create a new Controller/Views for those actions which you need to bypass the authorization.

And in the web.config add the following ,

 <location path="TheNameOfTheControllerYouWantToBypass">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>