如何在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); } }; });
资源:
https://www.illucit.com/blog/2016/04/asp-net-5-identity-302-redirect-vs-401-unauthorized-for-api-ajax-requests/
如果请求标头包含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
的调用中添加以下内容
上述就是C#学习教程:如何在ASP.NET Core中返回401而不是302?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
services.AddIdentity(o => { o.Cookies.ApplicationCookie.AutomaticChallenge = false; });
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1301136.html