我们有一个使用 OpenIdDict 进行身份验证的 asp.net 核心 Web 应用程序。我注意到我未经身份验证的 Ajax 调用在响应正文中返回 200 和我们的登录表单。从我读到的这是预期的行为,因为 OpenIdDict 处理请求,然后 ASP.NET 核心处理它并返回 200。ASP.NET 核心正在处理它,因为在 Startup.cs 中调用了“UseIdentity()”。我在 OpenIdDict 中看到的所有示例都调用了“UseIdentity”。我有2个问题。
options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents { OnRedirectToLogin = ctx => { if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == (int) HttpStatusCode.OK) { ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized; } else { ctx.Response.Redirect(ctx.RedirectUri); } return Task.FromResult(0); } };
代码示例来源:https : //devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/
在此处进一步讨论此问题:https : //github.com/aspnet/Security/issues/804
OpenIdDict 是否需要“UseIdentity()”?
不,在引擎盖下注册的 cookie 中间件app.UseIdentity()
不被 OpenIddict 直接使用,因此调用此方法不需要 OpenIddict 正常工作。
也就是说,如果您使用依赖 cookie 身份验证的 ASP.NET Core Identity 功能(几乎是AccountController
/ 中的所有内容ManageController
),那么是的,您必须使用app.UseIdentity()
.
我在 OpenIdDict 中看到的所有示例都调用了“UseIdentity”
对于不使用 的示例app.UseIdentity()
,您可以查看官方密码流示例或阅读这篇博客文章,其中展示了如何在没有 ASP.NET Core Identity 的情况下使用 OpenIddict。
如果我不想失去重定向登录 UI 视图的能力,这是实现这一点以覆盖 OnRedirectToLogin 的最佳/最简单/最安全的方法吗?
这绝对有效,但我个人选择了一个更安全的选项,即使用管道分支来排除app.UseIdentity()
. 这不仅可以防止 Identity 劫持 API 返回的 401 响应,还可以避免 XSRF 攻击,因为HttpContext.User
无法使用从 cookie 中提取的身份填充:
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), branch =>
{
branch.UseIdentity();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句