在 ASP.NET Core 8 中结合 GoogleOpenId 和 Cookie 身份验证

问题描述 投票:0回答:1

我有一个应用程序,其主要身份验证使用 cookie 和标准身份验证模式。我还想拥有 GoogleOpenId 身份验证,以便特定功能可以访问 Google 日历。

在program.cs中我有

builder.Services.AddAuthentication(options =>
    {
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.LoginPath = new PathString("/Account/Login");
    })
    .AddGoogleOpenIdConnect(GoogleOpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.ClientId = clientId;
        options.ClientSecret = clientSecret;
    });

然后在控制器中我有这样的东西

[Authorize(AuthenticationSchemes = GoogleOpenIdConnectDefaults.AuthenticationScheme)]
public async Task<IActionResult> GoogleAuth([FromServices] IGoogleAuthProvider auth)
{
    // ...
}

[Authorize]
public Task<IActionResult> RegularAuth()
{
    var claims = HttpContext.User.Claims;
}

现在的问题是我是否遵循流程

  1. 使用我的普通用户名/密码 cookie 身份验证登录。一切都好
  2. 然后转到 GoogleAuth 端点,它登录 Google 并返回,一切正常。

但是,如果我返回到 RegularAuth 端点,我的用户和声明已被 Google 令牌覆盖。我基本上需要同时拥有它们,我实际上经过了双重身份验证,具体取决于端点。

这怎么可能?

asp.net-core google-oauth
1个回答
0
投票

当然有可能。但这个项目需要 2 个 cookie 方案才能做到这一点。

GoogleOpenIdConnectDefaults.AuthenticationScheme
实际上需要一个“cookie方案”来在google登录后生成cookie。默认情况下,它将使用
CookieAuthenticationDefaults.AuthenticationScheme
。所以有冲突。您的“cookie auth”和“google auth”都使用
CookieAuthenticationDefaults.AuthenticationScheme
来保持登录状态。你可以看到他们在登录后都生成了一个具有相同名称的cookie
.AspNetCore.Cookies

enter image description here

所以你只需要为“google auth”添加另一个cookie方案,如下所示

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie("GoogleAuthCookieScheme", options =>
    {
        options.Cookie.Name = "MyGoogleAuth";
    })
    .AddGoogleOpenIdConnect(GoogleOpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.ClientId = "xxx";
        options.ClientSecret = "xxx";
        options.SignInScheme= "GoogleAuthCookieScheme";
    });
© www.soinside.com 2019 - 2024. All rights reserved.