3

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.

griegs
  • 22,624
  • 33
  • 128
  • 205

2 Answers2

8

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

Omri
  • 264
  • 1
  • 2
  • 2
    Hmmm, this is the standard mvc authorize attribute and i'm kinda loath to replace it for my own. thought there would be a nicer way – griegs Jan 20 '12 at 05:08
  • 1
    The only thing you're doing is adding in custom logic to look at the current build mode and either apply the authorization or not. You're not rolling your own, you've inherited from the filter so it performs exactly the same with the exception you requested. – Nick Bork Jan 20 '12 at 05:17
  • I have found that this does not work for OWIN WS-Federation authentication ... perhaps since OWIN is embedded as an app plug-in. Once OWIN is configured in startup, custom AuthorizeAttributes do not bypass it. – JasonInVegas Sep 20 '17 at 16:28
1

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 
Nick Bork
  • 4,831
  • 1
  • 24
  • 25
  • No the attribute is ignored no matter if i am in debug or release modes – griegs Jan 20 '12 at 05:03
  • Look at what Omri posted, its the alternative I suggested, creating your own Authorize filter and adding the directive in to the authorize event. – Nick Bork Jan 20 '12 at 05:08