Eri*_*c B 24 c# asp.net-core asp.net-core-identity
当用户未登录时,我试图让ASP.NET Core Identity返回401.我已经[Authorize]
为我的方法添加了一个属性,而不是返回401,它返回302.我已经尝试了很多建议但是似乎没什么用,包括services.Configure
和app.UseCookieAuthentication
设置LoginPath
为null
或PathString.Empty
.
Mat*_*kan 45
从ASP.NET Core 2.x开始:
services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});
Run Code Online (Sandbox Code Playgroud)
小智 15
如果请求标头包含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);
}
Run Code Online (Sandbox Code Playgroud)
请参阅gitHub:https://github.com/aspnet/Security/blob/5de25bb11cfb2bf60d05ea2be36e80d86b38d18b/src/Microsoft.AspNetCore.Authentication.Cookies/Events/CookieAuthenticationEvents.cs#L40-L52
Fra*_*osu 12
对于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.CompletedTask;
}
context.Response.Redirect(context.RedirectUri);
return Task.CompletedTask;
};
});
Run Code Online (Sandbox Code Playgroud)
Mar*_*rry 11
services.Configure<IdentityOptions>(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);
}
};
});
Run Code Online (Sandbox Code Playgroud)
资源:
好吧,在深入研究asp.net核心单元测试之后,我终于找到了一个可行的解决方案.您必须在通话中添加以下内容services.AddIdentity
services.AddIdentity<ApplicationUser, IdentityRole>(o => {
o.Cookies.ApplicationCookie.AutomaticChallenge = false;
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11038 次 |
最近记录: |