Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to disable authorization on one action in an MVC controller?

Tags:

asp.net-mvc

I have an authorization attribute on a controller, but I'd like to turn it off on one action. I created my own authorization filter and added "Anonymous" into the Roles list. In my filter I then return true if Anonymous appears in the role list.

However, it doesn't seem to get past the login page as if the controller authorization is pre-empting anything else.

like image 294
jaffa Avatar asked Mar 06 '12 09:03

jaffa


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 do I override an authorized attribute?

You could create a custom authorisation attribute inheriting from the standard AuthorizeAttribute with an optional bool parameter to specify whether authorisation is required or not. and for any controllers you don't want authorisation simply use the override with a 'false' - e.g.

Can we override action method in MVC?

If we have to overload the action Method in asp.net MVC then we can not do it directly. We have to change the ActionName like this code snippet. Now to run the controller GetEmpName action method with just give the URL like this: http://localhost:49389/Home/GetEmpName.


2 Answers

You can add [Authorize] To the controller class, and then add [AllowAnonymous] to the single action you don't want to be authorized. Example:

[Authorize] public class AccountController : Controller {     public ActionResult Profile()     {         return View();     }      [AllowAnonymous]     public ActionResult Login()     {         return View();     } } 
like image 198
Kyle Avatar answered Sep 22 '22 15:09

Kyle


You can create your own version of the attribute.

There is a very similar question and there is a pretty good answer how to implement your own attribute that handles this situation.

Override Authorize Attribute in ASP.NET MVC

Btw. you could also create your controller that would have authorization by default.

Base

[Authorize] public abstract class SecureControllerBase : Controller { } 

Usage

public class MyController : SecureControllerBase { } 
like image 26
Tx3 Avatar answered Sep 19 '22 15:09

Tx3