ASP MVC Authorize all actions except a few

前端 未结 7 624
逝去的感伤
逝去的感伤 2020-12-13 00:29

I have a controller and I would like to require Authorization for all actions by default except a couple. So in the example below all actions should require authentication e

相关标签:
7条回答
  • 2020-12-13 01:09

    Mark the controller with [Authorize]

    [Authorize] public class YourController : ApiController

    Mark actions you want public with :

    [AllowAnonymous]

    0 讨论(0)
  • 2020-12-13 01:09

    Little late to the party, but I ended up creating a Controller-level auth attribute and an Action-level auth attribute and just skipping over the Controller auth if the Action had its own Auth attribute. See code here:

    https://gist.github.com/948822

    0 讨论(0)
  • 2020-12-13 01:11

    MVC4 has a new attribute exactly meant for this [AllowAnonymous] (as pointed out by Enrico)

    [AllowAnonymous]
    public ActionResult Register()
    

    Read all about it here:

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

    0 讨论(0)
  • 2020-12-13 01:24

    Use a custom filter as described in Securing your ASP.NET MVC 3 Application.

    0 讨论(0)
  • 2020-12-13 01:25

    Ok, this is what I did. If there is a better way let me know.

    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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 01:28

    What about [AllowAnonymous] ??

    0 讨论(0)
提交回复
热议问题