Why doesn't SuppressFormsAuthenticationRedirect work in AuthorizeAttribute.HandleUnauthorizedRequest override?

限于喜欢 提交于 2019-12-08 17:40:29

问题


I've got an MVC 5.1 site with a controller with a single POST action. I have an Android app that I want to POST to it using basic authentication. I created a BasicAuthorizeAttribute class and applied it to my controller, and for testing purposes make it reject everything:

public class BasicAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return false;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
        base.HandleUnauthorizedRequest(filterContext);
    }
}

I can step through my HandleUnauthorizedRequest in the debugger, but Fiddler shows the POST response is a 302 redirect to the login page. I thought SuppressFormsAuthenticationRedirect was supposed to prevent that. It's a problem because the Android app follows the redirect and gets 200 OK from the login request, so it appears the POST succeeded. What am I doing wrong?


回答1:


The 200 OK status code is set upstream of the call to HandleUnauthorizedRequest. Explicitly clearing, setting and ending the response works. SuppressFormsAuthenticationRedirect doesn't appear to be necessary in this case.

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.HttpContext.Response.Clear();
    filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    filterContext.HttpContext.Response.End();
    base.HandleUnauthorizedRequest(filterContext);
}


来源:https://stackoverflow.com/questions/22335849/why-doesnt-suppressformsauthenticationredirect-work-in-authorizeattribute-handl

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