我在 ASP.NET Core 中使用身份验证中间件(无 身份)与社交提供商一起实现身份验证。事情正在使用以下配置:
services
.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.RequireAuthenticatedSignIn = false;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/account/logout";
})
.AddGoogle(options =>
{
options.ClientId = "...";
options.ClientSecret = "...";
options.Events = new OAuthEvents
{
OnTicketReceived = ctx =>
{
...
}
};
});
当将用户重定向到 Google 质询并且他们登录时,我的网站使用 cookie auth 成功进行了身份验证。
现在,我想更好地控制用户登录时应该发生的事情。我想在 OnTicketReceived
中验证一些要求,并在某些情况下禁止使用 cookie 身份验证登录。
为 OnTicketReceived
考虑这样的代码:
OnTicketReceived = ctx =>
{
if (someRequirementNotMet)
{
// User should not be logged in and redirected to /login
// CODE MISSING HERE!
}
if (someCondition)
{
// User should be logged in and redirected to /somepage
ctx.ReturnUri = "/somepage";
return Task.CompletedTask;
}
// User should be logged in and redirected to /someotherpage
ctx.ReturnUri = "/someotherpage";
return Task.CompletedTask;
}
我将如何实现这一目标?我试过这个:
ctx.ReturnUri = "/login";
return Task.CompletedTask;
在第一个 if
中。但是当重定向到 /login
时,用户已登录。我还尝试调用 ctx.HandleResponse()
但这只会生成一个空白结果。
最佳答案
我想出了如何解决这个问题:
OnTicketReceived = ctx =>
{
if (someRequirementNotMet)
{
// User should not be logged in and redirected to /login
ctx.HandleResponse();
ctx.Response.Redirect("/login");
return Task.CompletedTask;
}
if (someCondition)
{
// User should be logged in and redirected to /somepage
ctx.ReturnUri = "/somepage";
return Task.CompletedTask;
}
// User should be logged in and redirected to /someotherpage
ctx.ReturnUri = "/someotherpage";
return Task.CompletedTask;
}
关于authentication - 在 ASP.NET Core 中进行社交登录后,禁止并将用户重定向到其他页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60389802/