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

1

7

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?

Dup answered 11/3, 2014 at 20:24 Comment(0)
D
7

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);
}
Dup answered 12/3, 2014 at 14:12 Comment(3)
Thank you! I've been fighting this for a few hours. .End() does the trick. I thought this task was the very purpose of .SuppressFormsAuthenticationRedirect, so I really wonder where it would work (anywhere?) and why it doesn't here.Glut
This helped me solve a similar problem, but within Global.Application_Error() - Thanks a bunch!Plasticize
End() did the trick for me also. Bottom line: Microsoft like in many cases engineered ASP.NET MVC. It's just way to complex, don't get me started on authentication. I don't know why they don't develop things simple? Instead of wondering ah this works, but I don't know why. Like you mentioned SuppressFormsAuthenticationRedirect where it would work?Efface

© 2022 - 2024 — McMap. All rights reserved.