【问题标题】:Handle JWT Tokens with Google Auth使用 Google Auth 处理 JWT 令牌
【发布时间】:2022-07-19 19:58:31
【问题描述】:

我有一个针对我的 Web Api 进行身份验证的移动应用程序,我在成功登录后向用户发出 JWT 令牌,用户可以将其用于所有后续请求。这就是我当前设置 web api 的方式

.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ClockSkew = TimeSpan.Zero,
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["JwtSettings:ApplicationID"],
        ValidAudience = builder.Configuration["JwtSettings:ApplicationID"],
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:SecurityKey"]))
    };

})

现在我决定将 Google Auth 添加到我的应用程序中,这样我的用户就无需注册,只需使用 Google。所以我在我的代码下面添加了..

.AddGoogle(options =>
    {
        options.ClientId = "xxxxx";
        options.ClientSecret = "xxxxx";
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.SaveTokens = true;
        options.CorrelationCookie.SameSite = SameSiteMode.Lax;

    }).AddCookie(options =>
    {
        options.LoginPath = "/Account/Unauthorized/";
        options.AccessDeniedPath = "/Account/Forbidden/";
    });

登录成功后可以从google获取token...

var accessToken = await HttpContext.GetTokenAsync(CookieAuthenticationDefaults.AuthenticationScheme, "access_token");

现在,当我将此令牌传递给我的 webapi 时,它没有通过身份验证。我想使用 google 令牌对我的 webapi 进行身份验证,就像我对当前设置所做的一样。有可能吗?

【问题讨论】:

  • 嗨@user2404597,为什么你手动将令牌传递给你的webapi?常见的过程是在你的 webapi 项目中配置 Google 身份验证,然后将[Authorize] 添加到操作中。当您向授权操作发送请求时,它会将您重定向到谷歌登录。登录成功后即可成功进入操作。
  • @Rena 它是一个移动 Android 应用程序,这就是为什么我必须在每个请求中包含令牌。

标签: .net-core google-oauth asp.net-core-webapi


【解决方案1】:

有趣的是:这有助于https://stackoverflow.com/a/72389847/5574017

我在配置中添加了客户端 ID、客户端密码和颁发者。我还使用适当的配置添加了AddGoogle

这让我可以在 Bearer 中传递一个 Google JWT,并在每次 API 调用时对其进行验证。

【讨论】:

    猜你喜欢
    • 2017-04-06
    • 1970-01-01
    • 2017-06-10
    • 2015-08-26
    • 2020-12-05
    • 2016-10-20
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多