Bypass or turn off [Authorize(Roles=“”)] during development?

夙愿已清 提交于 2019-12-03 11:09:20

问题


Building an MVC3 application, and TPTB want us to use their custom authorization provider. However, during development this auth provider is kind of a pain, since it will either give an error til you shut down/restart the browser, or it will require you to re-log o on every compile.

For now, I just added <authentication mode="None"/> to the web.config, which works fine until I encounter an action or controller that uses the [Authorize(Roles = "Admin")] filter (it can be any role, not just Admin). When it hits one of those, it just renders a blank page.

Is there a way globally and temporarily turn these filters off? Or just give the user all roles while I'm in development?

EDIT

Let me clarify- I'm actually porting over a large app from MVC2 to MVC3. It has lots of [Authorize(Roles="Admin")] and [Authorize(Roles="Admin,Editor")] throughout it. I'd rather not change all of those if possible.

Should I just create a small custom role provider that gives all roles automatically?


回答1:


You could write a custom Authorize filter which will not perform any checks if the request is coming from localhost:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Request.Url.IsLoopback)
        {
            // It was a local request => authorize the guy
            return true;
        }

        return base.AuthorizeCore(httpContext);
    }
}



回答2:


You can inherit from AuthorizeAttribute and separate realizations with #if DEBUG directive.

public class MyAuthorizeAttribute: AuthorizeAttribute
{
#if DEBUG
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return true;
    }
#endif
}

Or #define YOUR_OWN_FLAG to turn behavior on and off in any build, debug or release.




回答3:


For Web API:

public class MyAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        return actionContext.Request.RequestUri.IsLoopback || base.IsAuthorized(actionContext);
    }
}


来源:https://stackoverflow.com/questions/13767527/bypass-or-turn-off-authorizeroles-during-development

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!