当我将 ASP.NET HTTP-StatusCode 硬编码为 401 时,我总是跳到登录页面?

发布于 2024-08-02 11:26:12 字数 901 浏览 5 评论 0原文

我有一个 API 设置。当用户提供无效/缺失的 API 密钥时,我尝试将 Response.StatusCode 设置为 401,但某些内容不断将我跳到登录页面。这是一个 API...所以我不想要那个。我希望向他们发送 json 错误消息,代码为 401。

此示例 api 的 url 为: /api/search/foo?apikey=12345&bar=hi+stack+overflow

我有什么做错了吗?

这是一些示例代码:-

// 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);

另外,我的 web.config 中有以下内容,如果这有帮助......

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

有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半山落雨半山空 2024-08-09 11:26:12

尝试在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);
    }
}

Try to handle the 401 in the Application_EndRequest of the Globals.asax.
You have the forms authentication mode set so it's doing what it's supposed to do, which is to redirect to the Login.aspx page on a 401 status code.

Your code becomes something like:

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);

And in the Application_EndRequest something like:

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);
    }
}
葬花如无物 2024-08-09 11:26:12

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

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

Because ASP.NET is handling the "401 Not authorised" status and bouncing the user to the login page - as that's how it handles a 401 message from the server.

You could try setting it to "403 Forbidden" instead, although I think ASP.NET also tends to send those to the login handler as well (which is a bit of a pain), or just a plain "400 Bad Request"

怎言笑 2024-08-09 11:26:12

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

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

<location />

web.config 中的元素并微调配置。
HTH

编辑:更多...

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

无论如何...

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

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

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

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

This behavior depends on the System.Web.Security.FormsAuthenticationModule that you are using (and is active by default if I can remember right). It monitors not only the AuthenticateRequest event, but also the EndRequest event looking for the HTTP code 401.
This is the way other modules (e.g. the System.Web.Security.UrlAuthorizationModule ) signal their "evaluations".

If your url is an API, perhaps you could use the

<location />

element in web.config and fine tune the configuration.
HTH

EDIT: something more...

I'm not sure that my suggestion will help you :-) Maybe Zhaph - Ben Duguid's idea is better.

Anyway...

Here is the reference for location Element. In short, you can decide a different set of configurations for a particular path. There is another way not completely equivalent: exploiting the hierarchical nature of .config files.

I assumed that your API is part of a bigger web application...

In your case you should evaluate if, for the URL /api/search/foo (in your example), you want a different behavior. If you need a different one, see the reference for "location" and try to figure out if you can switch off something.

If your application is "just" API, then you could remove all the modules that you don't need (in particular the FormsAuthenticationModule which is responsible for redirect).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文