When I hardcode ASP.NET HTTP-StatusCode to 401, do I always go back to the login page?

I have an API setup. When the user provides an invalid / missing API key, I try to set Response.StatusCode to 401, something keeps bouncing on my login page. This is an API ... so I don't want this. I want to send them a json error message with code 401.

url for this api sample: /api/search/foo?apikey=12345&bar=hi+stack+overflow

What did I do wrong?

Here is a sample code: -

// Do we have an Api Key that is legit?
if (!CheckAPIKey(context))
{
    json = JsonConvert.ExportToString("Invalid API key or no API key was provided.");
    context.Response.StatusCode = 401; // Not authorised.
}
else
{
    ... get json data ...
}

context.Response.Write(json);

Also, I have the following in my web.config, if that helps ...

<authentication mode="Forms">
    <forms loginUrl="~/Pages/Login.aspx" protection="Validation" timeout="1000000000" requireSSL="false" slidingExpiration="true" defaultUrl="Default.aspx">
    </forms>
</authentication>

Any ideas?

+3
source share
3 answers

401 Application_EndRequest Globals.asax. , , , Login.aspx 401.

- :

HttpContext context = HttpContext.Current;
// Do we have an Api Key that is legit?
if (!CheckAPIKey(context))
{
    context.Response.StatusCode = 401; // Not authorised.
}
else
{
    ... get json data ...
}
context.Response.Write(json);

Application_EndRequest - :

protected void Application_EndRequest(object sender, EventArgs e)
{
    HttpContext context = HttpContext.Current;
    if (Response.StatusCode == 401)
    {
        Response.ClearContent();
        json = JsonConvert.ExportToString("Invalid API key or no API key was provided.");
        context.Response.Write(json);
    }
}
+3

ASP.NET "401 " - , 401 .

"403 Forbidden", , ASP.NET ( ) "400 Bad Request" "

+1

System.Web.Security.FormsAuthenticationModule, ( , ). AuthenticateRequest, EndRequest, HTTP- 401. , (, System.Web.Security.UrlAuthorizationModule) "".

URL- API, ,

<location />

web.config .

EDIT: - ...

, :-) , Zhaph - Ben Duguid .

...

. , . , : .config.

, API -...

, URL/api/search/foo ( ) . , . "location" , - .

"" API, , ( , FormsAuthenticationModule, ).

0

Source: https://habr.com/ru/post/1715309/


All Articles