如何从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屋!