3

I've got an API setup. When the user provides an invalid/missing API key, I'm trying to set the Response.StatusCode to 401, something keeps bouncing me to my login page. It's an API ... so I don't want that. I wish to send them the json error message with the code being 401.

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

What have I done wrong?

Here's some 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 this helps...

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

Any ideas?

4

3 回答 3

3

尝试处理 Globals.asax 的 Application_EndRequest 中的 401。您设置了表单身份验证模式,因此它正在做它应该做的事情,即重定向到 401 状态代码上的 Login.aspx 页面。

您的代码如下所示:

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);
    }
}
于 2010-01-08T18:34:48.523 回答
1

因为 ASP.NET 正在处理“401 未授权”状态并将用户弹回登录页面 - 因为这就是它处理来自服务器的 401 消息的方式。

您可以尝试将其设置为“403 Forbidden”,尽管我认为 ASP.NET 也倾向于将这些发送到登录处理程序(这有点痛苦),或者只是一个简单的“400 Bad Request”

于 2009-08-17T10:32:44.757 回答
0

此行为取决于您正在使用的 System.Web.Security.FormsAuthenticationModule (如果我没记错的话,默认情况下是活动的)。它不仅监视 AuthenticateRequest 事件,还监视寻找 HTTP 代码 401 的 EndRequest 事件。这是其他模块(例如 System.Web.Security.UrlAuthorizationModule )发出“评估”信号的方式。

如果您的网址是 API,也许您可​​以使用

<location />

web.config 中的元素并微调配置。高温高压

编辑:更多...

我不确定我的建议是否会对您有所帮助:-) 也许Zhaph - Ben Duguid的想法更好。

反正...

这是location Element的参考。简而言之,您可以为特定路径决定一组不同的配置。还有另一种不完全等效的方法:利用 .config 文件的分层特性。

我假设您的 API 是更大的 Web 应用程序的一部分...

在您的情况下,您应该评估对于 URL /api/search/foo (在您的示例中),您是否想要不同的行为。如果您需要不同的,请参阅“位置”参考并尝试确定您是否可以关闭某些东西。

如果您的应用程序“只是”API,那么您可以删除所有不需要的模块(特别是负责重定向的 FormsAuthenticationModule)。

于 2009-08-17T10:47:19.407 回答