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

标签 authentication asp.net-core

我在 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/

相关文章:

ios - Instagram API 返回 400(错误请求)

authentication - 在 docker 中运行的 GUI 应用程序的 X11 转发

c# - EF Core开发过程中如何处理数据库变化?

c# - 没有指定 authenticationScheme,也没有找到基于自定义策略的授权的 DefaultForbidScheme

c# - 以 asp-for 作为参数的自定义 ViewComponent

ios - 编码 iOS 基本身份验证

Docker Jupyter token 认证 : Invalid Credential

java - 请确保至少有一个领域可以验证这些 token

c# - 如何将字符串传递给 Angular 中的发布请求?

c# - 如何在 ConfigureServices 方法中使用 ASP.NET Core 2.1 读取用户环境变量?