ASP MVC授权除少数之外的所有操作

时间:2009-04-23 05:51:03

标签: asp.net asp.net-mvc

我有一个控制器,除了一对夫妇之外,我希望默认情况下对所有操作进行授权。因此,在下面的示例中,除索引外,所有操作都需要身份验证。我不想用Authorize来装饰每个动作,我只想在某些情况下覆盖默认授权,可能使用自定义过滤器,例如NotAuthorize。

[Authorize]
public class HomeController : BaseController
{
    [NotAuthorize]
    public ActionResult Index()
    {
        // This one wont
        return View();
    }

    public ActionResult About()
    {
        // This action will require authorization
        return View();
    }
}

7 个答案:

答案 0 :(得分:39)

好的,这就是我的所作所为。如果有更好的方式让我知道。

public class NotAuthorizeAttribute : FilterAttribute
{
    // Does nothing, just used for decoration
}

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Check if this action has NotAuthorizeAttribute
        object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
        if (attributes.Any(a => a is NotAuthorizeAttribute)) return;

        // Must login
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

答案 1 :(得分:28)

[AllowAnonymous] ??

怎么样?

答案 2 :(得分:9)

MVC4有一个新属性,正好适用于此[AllowAnonymous](正如Enrico所指出的)

[AllowAnonymous]
public ActionResult Register()

在这里阅读所有相关内容:

http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx

答案 3 :(得分:6)

这就是我要做的事情,类似于Craig的答案,有几处改变:

1)创建一个派生自System.Attribute的普通属性(不需要派生自FilterAttribute,因为您不会使用任何FilterAttribute提供的内容)。

也许创建属性的类层次结构,以便您可以根据层次结构进行测试,例如

Attribute
    AuthorizationAttribute
         AuthorizationNotRequiredAttribute
         AuthorizationAdminUserRequiredAttribute
             AuthorizationSuperUserRequiredAttribute

2)在BaseController中覆盖OnAuthorization方法而不是OnActionExecuting方法:

protected override void OnAuthorization(AuthorizationContext filterContext)
{
    var authorizationAttributes = filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AuthorizationAttribute>();
    bool accountRequired = !authorizationAttributes.Any(aa => aa is AuthorizationNotRequiredAttribute);

我喜欢默认安全的方法:即使您忘记在Action上添加属性,它至少也需要用户登录。

答案 4 :(得分:6)

使用Securing your ASP.NET MVC 3 Application中描述的自定义过滤器。

答案 5 :(得分:5)

使用[授权]

标记控制器

[授权] public class YourController:ApiController

标记您想要公开的行动:

[使用AllowAnonymous]

答案 6 :(得分:1)

参加派对的时间不多,但我最终创建了一个Controller级别的auth属性和一个Action级别的auth属性,如果Action有自己的Auth属性,则跳过Controller auth。请参阅此处的代码:

https://gist.github.com/948822