griegs
griegs

Reputation: 22760

MVC Authorize Attribute for Release Version only

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.

Upvotes: 3

Views: 2966

Answers (2)

Omri
Omri

Reputation: 264

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

Upvotes: 8

Nick Bork
Nick Bork

Reputation: 4841

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 

Upvotes: 1

Related Questions