如何在ASP.NET Core中返回401而不是302?
当用户未登录时,我正在尝试让ASP.NET Core Identity返回401.我已经为我的方法添加了[Authorize]
属性,而不是返回401,它返回302.我试过了一吨建议但似乎没有任何效果,包括services.Configure
和app.UseCookieAuthentication
将LoginPath
设置为null
或PathString.Empty
。
从ASP.NET Core 2.x开始 :
services.ConfigureApplicationCookie(options => { options.Events.OnRedirectToLogin = context => { context.Response.StatusCode = 401; return Task.CompletedTask; }; });
services.Configure(options => { options.Cookies.ApplicationCookie.LoginPath = new PathString("/"); options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = context => { if (context.Request.Path.Value.StartsWith("/api")) { context.Response.Clear(); context.Response.StatusCode = 401; return Task.FromResult(0); } context.Response.Redirect(context.RedirectUri); return Task.FromResult(0); } }; });
资源:
如果请求标头包含X-Requested-With:XMLHttpRequest,则状态代码将为401而不是302
private static bool IsAjaxRequest(HttpRequest request) { return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) || string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal); }
请参阅gitHub: https : //github.com/aspnet/Security/blob/5de25bb11cfb2bf60d05ea2be36e80d86b38d18b/src/Microsoft.AspNetCore.Authentication.Cookies/Events/CookieAuthenticationEvents.cs#L40-L52
对于Asp.net Core 2,请使用此安装程序
services.ConfigureApplicationCookie(options => { options.LoginPath = new PathString("/Account/Login"); options.LogoutPath = new PathString("/Account/Logout"); options.Events.OnRedirectToLogin = context => { if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == StatusCodes.Status200OK) { context.Response.Clear(); context.Response.StatusCode = StatusCodes.Status401Unauthorized; return Task.FromResult
好吧,在深入研究asp.net核心unit testing之后,我终于找到了一个可行的解决方案。 您必须在对services.AddIdentity
的调用中添加以下内容
services.AddIdentity(o => { o.Cookies.ApplicationCookie.AutomaticChallenge = false; });
- 在asp .Net Core项目中添加wsdl web引用
- 在ASP.NET Core中的Program.Main中访问环境名称
- 覆盖AspNet.Security.OpenIdConnect.Server中的TokenEndPoint
- 在ASP.NET Core中使用DirectoryServices
- ASP.NET核心本地化 – 不从资源文件返回值,仅返回Name
- ASP.NET 5 beta 8中的Windows身份validation支持
- 没有配置身份validation处理程序来validation该方案:Microsoft.AspNet.Identity.External
- ASP.NET核心中的承载令牌认证
- 在ASP.NET Core中到达控制器之前拦截错误请求