在回答这个问题之后,默认情况下,我使用以下代码对所有内容添加了授权:
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)。
我希望它仅返回HTTP 401,而不是重定向。
如何在ASP.NET 5中为WebAPI执行此操作?
我在Angular2 + ASP.NET Core应用程序中遇到了这个问题。我设法通过以下方式对其进行了修复:
services.AddIdentity<ApplicationUser, IdentityRole>(config => {
// ...
config.Cookies.ApplicationCookie.AutomaticChallenge = false;
// ...
});
如果这对你不起作用,则可以尝试使用以下方法:
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选项:
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);
}
};
});
问题/澄清-为什么我们在更改HTTP 200之前先检查一下它?如果重定向发生,我们是否应该采取行动?提前致谢。
相应地更新了答案。
好的答案,指出了我正确的方向。您可能还想将OnRedirectToAccessDenied用于经过身份验证(登录)的用户,而不要使用具有HttpStatusCode.Forbidden的授权用户(对于api情况),以及不带ReturnString的重定向(对于View用户)。
这是ASP.NET MVC Core和Angular 2应用程序的正确答案。谢谢!!!!开车给我bun堡。注意:通过cookie使用JWT令牌认证时,这是必需的-尤其是从JWT承载认证切换时。
似乎不适用于.NET Core 3.0(预览版):/