在ASP.NET Core中进行社交登录后,禁止用户并将其重定向到其他页面



我正在ASP.NET Core中使用身份验证中间件(noIdentity(与社交提供商实现身份验证。以下配置可以正常工作:

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 =>
{
...
}
};
});

当用户重定向到谷歌挑战并登录时,我的网站成功地通过cookie身份验证。

现在,我想更好地控制用户登录时应该发生的事情。我想验证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;

在第一CCD_ 3内部。但是当重定向到/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;
}

最新更新