Asp.net core 如何响应ASP.NET 5 ASP.NET Identity 3.0 RC1上的状态401
在我使用的所有教程中Asp.net core 如何响应ASP.NET 5 ASP.NET Identity 3.0 RC1上的状态401,asp.net-core,http-status-code-401,asp.net-identity-3,Asp.net Core,Http Status Code 401,Asp.net Identity 3,在我使用的所有教程中 app.UseCookieAuthentication(ctx => { ctx.AutomaticChallenge = true; ctx.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = context =>
app.UseCookieAuthentication(ctx =>
{
ctx.AutomaticChallenge = true;
ctx.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = context =>
{
context.Response.Headers["Location"] = context.RedirectUri;
context.Response.StatusCode = 401;
return Task.FromResult(0);
}
};
});
将需要创建状态代码为401的重定向,但由于我使用ASP.NET标识,我总是自动重定向到帐户/登录页面
一些广域网可以帮助我,告诉我如何不被重定向到帐户/登录,只返回401状态。
如果我使用任何其他状态,如403,工作正常,但401,我可以返回。
谢谢。此修复程序用于将其添加到身份提供程序,而不是作为其自己的身份验证步骤 因此: 而是将cookie设置添加到标识配置:
public void ConfigureServices(IServiceCollection services)
{
...
// Configure identity service
services.AddIdentity<AppUser, AppRole>(options =>
{
// Set cookie options for that service
var ctx = options.Cookies.ApplicationCookie;
// Your code
ctx.AutomaticChallenge = true;
ctx.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
context.Response.Headers["Location"] = context.RedirectUri;
context.Response.StatusCode =
(int) HttpStatusCode.Unauthorized;
return Task.CompletedTask;
}
};
});
public void配置服务(IServiceCollection服务)
{
...
//配置标识服务
服务.附加性(选项=>
{
//为该服务设置cookie选项
var ctx=options.Cookies.applicationcokie;
//你的代码
ctx.AutomaticChallenge=true;
ctx.Events=新CookieAuthenticationEvents
{
OnRedirectToLogin=上下文=>
{
context.Response.Headers[“Location”]=context.RedirectUri;
context.Response.StatusCode=
(int)HttpStatusCode。未经授权;
返回Task.CompletedTask;
}
};
});
那么为什么要使用身份中间件呢?是的,这是一个很好的问题,但我想为用户和其他具有授权属性的实体使用EF身份实现,但我也希望如果我有WEB API返回401而不是状态200,因为它被重定向。我实际上正在尝试这种方法:我想你可以创建自己的MIDLEW如果您在cookie身份验证/身份验证之后运行重定向,请选择重定向并将其更改为401。感谢您的评论,但我认为我将使用IdentityServer3,因为我做所有这些都是为了保护我的API调用,也许IdentityServer3是目前最好的解决方案,而其他方法对于现在回复我。非常感谢您的评论。您对我的决定帮助很大。我会使用:context.Response.StatusCode=(int)HttpStatusCode.Unauthorized;return Task.CompletedTask;
稍微好一点
public void ConfigureServices(IServiceCollection services)
{
...
// Configure identity service
services.AddIdentity<AppUser, AppRole>(options =>
{
// Set cookie options for that service
var ctx = options.Cookies.ApplicationCookie;
// Your code
ctx.AutomaticChallenge = true;
ctx.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
context.Response.Headers["Location"] = context.RedirectUri;
context.Response.StatusCode =
(int) HttpStatusCode.Unauthorized;
return Task.CompletedTask;
}
};
});