使用AspNet Core 2.0进行Google JWT身份验证

Mik*_*g36 5 google-api google-authentication oauth-2.0 asp.net-core asp.net-core-2.0

我试图在我的ASP.NET Core 2.0 web api中集成google身份验证,我无法弄清楚如何让它工作.

我在我的Startup.cs中有这个代码ConfigureServices:

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders();

services.AddAuthentication()
.AddGoogle(googleOptions => 
 {
     googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
     googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});
Run Code Online (Sandbox Code Playgroud)

这个在Configure(IApplicationBuilder app, IHostingEnvironment env):

 app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

当我导航到Authorized端点时,结果是302 Found因为它可能是重定向到某个登录端点(我从未创建过).如何阻止重定向,只是让API期望一个令牌,401如果没有提供令牌,则返回一个令牌?

Mik*_*g36 14

为后代发布我的终极方法.

正如Tratcher指出的那样,AddGoogle中间件实际上并不适用于JWT身份验证流程.经过更多的研究,我意识到我最终想要的是这里描述的内容:https: //developers.google.com/identity/sign-in/web/backend-auth

所以我的下一个问题是

  1. 我不能再依赖标准的dotnet核心Jwt auth中间件,因为我需要将谷歌令牌验证委托给谷歌图书馆
  2. 没有C#google验证器列为该页面上的外部客户端库之一.

更挖掘后,我发现这是智威汤逊验证支持添加到C#在这里使用这个类和方法: Google.Apis.Auth.Task<GoogleJsonWebSignature.Payload> ValidateAsync(string jwt, GoogleJsonWebSignature.ValidationSettings validationSettings)

接下来我需要弄清楚如何替换内置的JWT验证.从这个问题我想出了一个方法: ASP.NET核心JWT承载令牌自定义验证

这是我的自定义GoogleTokenValidator:

public class GoogleTokenValidator : ISecurityTokenValidator
{
    private readonly JwtSecurityTokenHandler _tokenHandler;

    public GoogleTokenValidator()
    {
        _tokenHandler = new JwtSecurityTokenHandler();
    }

    public bool CanValidateToken => true;

    public int MaximumTokenSizeInBytes { get; set; } = TokenValidationParameters.DefaultMaximumTokenSizeInBytes;

    public bool CanReadToken(string securityToken)
    {
        return _tokenHandler.CanReadToken(securityToken);
    }

    public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
    {
        validatedToken = null;
        var payload = GoogleJsonWebSignature.ValidateAsync(securityToken, new GoogleJsonWebSignature.ValidationSettings()).Result; // here is where I delegate to Google to validate

        var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, payload.Name),
                    new Claim(ClaimTypes.Name, payload.Name),
                    new Claim(JwtRegisteredClaimNames.FamilyName, payload.FamilyName),
                    new Claim(JwtRegisteredClaimNames.GivenName, payload.GivenName),
                    new Claim(JwtRegisteredClaimNames.Email, payload.Email),
                    new Claim(JwtRegisteredClaimNames.Sub, payload.Subject),
                    new Claim(JwtRegisteredClaimNames.Iss, payload.Issuer),
                };

        try
        {
            var principle = new ClaimsPrincipal();
            principle.AddIdentity(new ClaimsIdentity(claims, AuthenticationTypes.Password));
            return principle;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs,我还需要清除默认的JWT验证,并添加我的自定义:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            })
            .AddJwtBearer(o =>
                {
                    o.SecurityTokenValidators.Clear();
                    o.SecurityTokenValidators.Add(new GoogleTokenValidator());
                }
Run Code Online (Sandbox Code Playgroud)

也许有一种更简单的方法,但这是我降落的地方,似乎工作正常!我做了额外的工作,为了简单起见,我离开了这里,例如,检查我的用户的数据库中是否已有用户与谷歌提供的声明匹配,所以如果上面的代码不是100%工作,我很抱歉我可能无意中删除了一些东西.

  • 您验证它是一个有效的令牌,但不是用于您的站点的令牌。您需要传递您在 google 中设置的受众(clientId)以提供额外的安全级别。您可以通过添加到 `new GoogleJsonWebSignature.ValidationSettings()` 并设置属性 `Audience = "YourClientId"` 来完成此操作。如果你不设置这个,谷歌验证会根据我的知识跳过受众验证。 (4认同)
  • 此答案所需的用途:使用 Google.Apis.Auth;使用系统;使用 System.Collections.Generic;使用 System.Security.Claims;使用 Microsoft.IdentityModel.Tokens;使用 System.IdentityModel.Tokens.Jwt; (2认同)

khe*_*ang 10

我刚刚发布了一个NuGet包来处理Google OpenID Connect令牌的验证.

该软件包依赖于微软的智威汤逊验证和认证处理Microsoft.AspNetCore.Authentication.JwtBearer,并增加了一些验证周围托管域.

它包含一个单一的公共扩展方法UseGoogle,就JwtBearerOptions可以让你配置该处理程序来验证谷歌ID连接令牌,没有其他的依赖关系:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(jwt => jwt.UseGoogle(
        clientId: "<client-id-from-Google-API-console>",
        hostedDomain: "<optional-hosted-domain>"));
Run Code Online (Sandbox Code Playgroud)

如果您想查看源代码,可以在此处找到它.