Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC Authorize all actions except a few

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 except the Index. I don't want to decorate every action with the Authorize, I just want to override the default authorization in certain circumstances probably with a custom filter such as 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();     } } 
like image 749
Craig Avatar asked Apr 23 '09 05:04

Craig


People also ask

How do you restrict access to action in MVC?

To restrict the public action method in MVC, we can use the “NonAction” attribute. The “NonAction” attribute exists in the “System. Web.

How authorization attribute works in MVC?

If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.

Can one action method have multiple views?

Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.

How do I Authorize in MVC 5?

Usage. Then you can start using [Authorize] attribute in Controller and Action methods. [Authorize(Roles = "Power Users")] public class UsersController : Controller { // ... }


2 Answers

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();         }     } } 
like image 173
Craig Avatar answered Sep 21 '22 15:09

Craig


What about [AllowAnonymous] ??

like image 45
Enrico Avatar answered Sep 19 '22 15:09

Enrico