Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Authorize Attribute for Release Version only

Tags:

c#

asp.net-mvc

Is it possible to decorate the class with;

[Authorize(Roles = "Admin")]

But have it only apply when you build the application in Release mode?

So in debug mode, the authorize is not applied and you can get to the admin pages without the need to log in.

My admin screens do not require any special user information, only whether you are logged in or not.

like image 750
griegs Avatar asked Feb 15 '26 20:02

griegs


2 Answers

One way is to create a custom Authorize attribute and then use #if DEBUG like this:

public class SwitchableAuthorizationAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    bool disableAuthentication = false;

    #if DEBUG
    disableAuthentication = true;
    #endif

    if (disableAuthentication)
        return true;

    return base.AuthorizeCore(httpContext);
}
}

copied from here: http://www.diaryofaninja.com/blog/2011/07/24/writing-your-own-custom-aspnet-mvc-authorize-attributes

like image 137
Omri Avatar answered Feb 18 '26 11:02

Omri


You can set compiler directives:

 #if DEBUG
  //Add code here
  #else
  //add code here
  #endif

But I'm not positive they will work with Metadata attributes. You could also create your own custom Authorize filter by inheriting from the one included with MVCm override the validation method and then include the code I've outlines as part audit so you bypass it when in debugmode, just never compile in DEBUG and deploy it.

You could also check to see if the debugger is attached in your custom authorize filter:

 System.Diagnostics.Debugger.IsAttached 
like image 22
Nick Bork Avatar answered Feb 18 '26 11:02

Nick Bork



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!