我在控制器上有一个授权属性,但我想在一个动作中关闭它。 我创建了我自己的授权筛选器,并将“匿名”添加到角色列表中。在我的过滤器中,如果Anonymous出现在角色列表中,则返回true。是否可以禁用MVC控制器中的一个操作的授权?
但是,它似乎没有通过登录页面,就好像控制器授权是抢占其他任何东西一样。
我在控制器上有一个授权属性,但我想在一个动作中关闭它。 我创建了我自己的授权筛选器,并将“匿名”添加到角色列表中。在我的过滤器中,如果Anonymous出现在角色列表中,则返回true。是否可以禁用MVC控制器中的一个操作的授权?
但是,它似乎没有通过登录页面,就好像控制器授权是抢占其他任何东西一样。
您可以将[Authorize]
添加到控制器类,然后将[AllowAnonymous]
添加到您不希望被授权的单一操作。例如:
[Authorize]
public class AccountController : Controller
{
public ActionResult Profile()
{
return View();
}
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
}
这只适用于MVC4及更高版本,但它可以很好地工作 – Nathan 2013-02-27 11:28:39
不要在您不需要的操作方法上添加AuthorizationAttribute。
我的自定义属性
public class AuthorizationFilterAttribute : AuthorizeAttribute
{
Some code...
}
我控制器
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
}
}
我希望你有我点什么,我想说你。
=================更新回答========================== ===================== 创建一个像下面这样的属性。
public sealed class AnonymousAttribute : Attribute { }
请将下面的代码放在您的OnAuthorization方法中。
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);
}
}
您可以创建自己的属性版本。
有一个非常相似的问题,并且有一个相当不错的答案,如何实现自己的属性来处理这种情况。
Override Authorize Attribute in ASP.NET MVC
Btw。你也可以创建你的控制器,默认情况下会有授权。
基地
[Authorize]
public abstract class SecureControllerBase : Controller
{
}
使用
public class MyController : SecureControllerBase
{
}
属性只需添加到您要筛选的操作,而不是在控制器类。通过不装饰动作,只要控制器或其基控制器之一没有获得该属性,它们就不会被过滤。
我想要规则的例外,所以打开控制器,关闭一个动作。 – jaffa 2012-03-14 10:58:45
我刚刚做了一个使用Azure ACS作为联合身份提供程序的解决方案,并且接受的答案对我无效。对于那些正在挣扎的人来说,我的解决方案是完全绕过所需的控制器/视图的安全。
为您需要绕过授权的操作创建新的Controller/Views。
并在网上。config添加以下内容:
<location path="TheNameOfTheControllerYouWantToBypass">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
'(1):'不知道我理解你,有些代码会很好。 '(2):'您可以在操作方法上添加授权属性。 – gideon 2012-03-06 09:54:31
您可以创建属性的自己的版本。 http://stackoverflow.com/questions/746998/override-authorize-attribute-in-asp-net-mvc – Tx3 2012-03-06 10:08:16
哎,大家似乎都不理解你:)。我明白,但我想要一个解决方案,因为我有同样的问题。你在此期间找到了什么? – 2012-12-10 12:03:09