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(); } }
To restrict the public action method in MVC, we can use the “NonAction” attribute. The “NonAction” attribute exists in the “System. Web.
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.
Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.
Usage. Then you can start using [Authorize] attribute in Controller and Action methods. [Authorize(Roles = "Power Users")] public class UsersController : Controller { // ... }
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(); } } }
What about [AllowAnonymous]
??
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With