如何从 ASP.NET Core webapi 中删除重定向并返回 HTTP 401? [英] How to remove the redirect from an ASP.NET Core webapi and return HTTP 401?
问题描述
按照这个问题的答案,我默认对所有内容都添加了授权,使用以下代码:
Following the answer on this question, I have added authorization on everything by default, using the following code:
public void ConfigureServices(IServiceCollection aServices)
{
aServices.AddMvc(options =>
{
var lBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();
var lFilter = new AuthorizeFilter(lBuilder.Build());
options.Filters.Add(lFilter);
});
aServices.AddMvc();
}
public void Configure(IApplicationBuilder aApp, IHostingEnvironment aEnv, ILoggerFactory aLoggerFactory)
{
aApp.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = "Cookies";
options.AutomaticAuthentication = true;
});
}
然而,当有人试图访问未经授权的内容时,它会返回一个(似乎是默认的)重定向 URL (http://foo.bar/Account/Login?ReturnUrl=%2Fapi%2Ffoobar%2F).
However when someone tries to access something unauthorized, it returns a (what seems a default) redirect URL (http://foo.bar/Account/Login?ReturnUrl=%2Fapi%2Ffoobar%2F).
我希望它只返回 HTTP 401,而不是重定向.
I want it to return a HTTP 401 only, instead of a redirect.
如何在 ASP.NET 5 中为 WebAPI 执行此操作?
How can I do this in ASP.NET 5 for a WebAPI?
推荐答案
我在 Angular2 + ASP.NET Core 应用程序中遇到了这个问题.我设法通过以下方式修复它:
I had with this problem in an Angular2 + ASP.NET Core application. I managed to fix it in the following way:
services.AddIdentity<ApplicationUser, IdentityRole>(config => {
// ...
config.Cookies.ApplicationCookie.AutomaticChallenge = false;
// ...
});
如果这对您不起作用,您可以尝试使用以下方法:
If this is not working for you, you can try with the following method instead:
services.AddIdentity<ApplicationUser, IdentityRole>(config => {
// ...
config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api"))
{
ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
// added for .NET Core 1.0.1 and above (thanks to @Sean for the update)
ctx.Response.WriteAsync("{"error": " + ctx.Response.StatusCode + "}");
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
}
return Task.FromResult(0);
}
};
// ...
}
Asp.Net Core 2.0 的更新
Cookie 选项现在配置如下:
Cookie options are now configured in the following way:
services.ConfigureApplicationCookie(config =>
{
config.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = ctx => {
if (ctx.Request.Path.StartsWithSegments("/api"))
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else {
ctx.Response.Redirect(ctx.RedirectUri);
}
return Task.FromResult(0);
}
};
});
这篇关于如何从 ASP.NET Core webapi 中删除重定向并返回 HTTP 401?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!