validationGoogle Id令牌

我正在使用ASP.NET Core为Android客户端提供API。 Android以Google帐户登录,并将ID令牌JWT传递给API作为持票人令牌。 我有应用程序工作,它确实通过了身份validation检查,但我不认为它正在validation令牌签名。

根据Google的文档,我可以将此url称为https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123 ,但我无法在服务器端找到相应的挂钩来执行此操作。 另外根据Google文档,我可以以某种方式使用客户端访问API来执行此操作,而无需每次都调用服务器。

我的配置代码:

app.UseJwtBearerAuthentication( new JwtBearerOptions() { Authority = "https://accounts.google.com", Audience = "hiddenfromyou.apps.googleusercontent.com", TokenValidationParameters = new TokenValidationParameters() { ValidateAudience = true, ValidIssuer = "accounts.google.com" }, RequireHttpsMetadata = false, AutomaticAuthenticate = true, AutomaticChallenge = false, }); 

如何让JWTBearer中间件validation签名? 我已经接近放弃使用MS中间件并自己动手了。

您可以通过几种不同的方式validation服务器端ID令牌的完整性:

  1. “手动” – 不断下载Google的公钥,validation签名,然后是每个字段,包括iss one; 主要优势(虽然我认为是一个小优势)我在这里看到的是,您可以最大限度地减少发送给Google的请求数量。
  2. “自动” – 在Google端点上执行GET以validation此令牌https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
  3. 使用Google API客户端库 – 就像官方的一样。

以下是第二个看起来如何:

 private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}"; public ProviderUserDetails GetUserDetails(string providerToken) { var httpClient = new MonitoredHttpClient(); var requestUri = new Uri(string.Format(GoogleApiTokenInfoUrl, providerToken)); HttpResponseMessage httpResponseMessage; try { httpResponseMessage = httpClient.GetAsync(requestUri).Result; } catch (Exception ex) { return null; } if (httpResponseMessage.StatusCode != HttpStatusCode.OK) { return null; } var response = httpResponseMessage.Content.ReadAsStringAsync().Result; var googleApiTokenInfo = JsonConvert.DeserializeObject(response); if (!SupportedClientsIds.Contains(googleApiTokenInfo.aud)) { Log.WarnFormat("Google API Token Info aud field ({0}) not containing the required client id", googleApiTokenInfo.aud); return null; } return new ProviderUserDetails { Email = googleApiTokenInfo.email, FirstName = googleApiTokenInfo.given_name, LastName = googleApiTokenInfo.family_name, Locale = googleApiTokenInfo.locale, Name = googleApiTokenInfo.name, ProviderUserId = googleApiTokenInfo.sub }; } 

GoogleApiTokenInfo类:

 public class GoogleApiTokenInfo { ///  /// The Issuer Identifier for the Issuer of the response. Always https://accounts.google.com or accounts.google.com for Google ID tokens. ///  public string iss { get; set; } ///  /// Access token hash. Provides validation that the access token is tied to the identity token. If the ID token is issued with an access token in the server flow, this is always /// included. This can be used as an alternate mechanism to protect against cross-site request forgery attacks, but if you follow Step 1 and Step 3 it is not necessary to verify the /// access token. ///  public string at_hash { get; set; } ///  /// Identifies the audience that this ID token is intended for. It must be one of the OAuth 2.0 client IDs of your application. ///  public string aud { get; set; } ///  /// An identifier for the user, unique among all Google accounts and never reused. A Google account can have multiple emails at different points in time, but the sub value is never /// changed. Use sub within your application as the unique-identifier key for the user. ///  public string sub { get; set; } ///  /// True if the user's e-mail address has been verified; otherwise false. ///  public string email_verified { get; set; } ///  /// The client_id of the authorized presenter. This claim is only needed when the party requesting the ID token is not the same as the audience of the ID token. This may be the /// case at Google for hybrid apps where a web application and Android app have a different client_id but share the same project. ///  public string azp { get; set; } ///  /// The user's email address. This may not be unique and is not suitable for use as a primary key. Provided only if your scope included the string "email". ///  public string email { get; set; } ///  /// The time the ID token was issued, represented in Unix time (integer seconds). ///  public string iat { get; set; } ///  /// The time the ID token expires, represented in Unix time (integer seconds). ///  public string exp { get; set; } ///  /// The user's full name, in a displayable form. Might be provided when: /// The request scope included the string "profile" /// The ID token is returned from a token refresh /// When name claims are present, you can use them to update your app's user records. Note that this claim is never guaranteed to be present. ///  public string name { get; set; } ///  /// The URL of the user's profile picture. Might be provided when: /// The request scope included the string "profile" /// The ID token is returned from a token refresh /// When picture claims are present, you can use them to update your app's user records. Note that this claim is never guaranteed to be present. ///  public string picture { get; set; } public string given_name { get; set; } public string family_name { get; set; } public string locale { get; set; } public string alg { get; set; } public string kid { get; set; } } 

根据这个github 问题 ,您现在可以使用GoogleJsonWebSignature.ValidateAsync方法来validationGoogle签名的JWT。 只需将idToken字符串传递给方法即可。

 var validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken); Assert.NotNull(validPayload); 

如果它不是有效的,它将返回null

请注意,要使用此方法,您需要直接安装Google.Apis.Auth nuget。

谷歌在openId connect的文档中说明

出于调试目的,您可以使用Google的tokeninfo端点。 假设您的ID令牌的值是XYZ123。

您不应该使用该端点来validation您的JWT。

validationID令牌需要几个步骤:

  1. validationID令牌是否由颁发者正确签名。 Google发布的令牌使用在发现文档的jwks_uri字段中指定的URI中找到的证书之一进行签名。
  2. validationID令牌中的iss值是否等于https://accounts.google.com或accounts.google.com。
  3. validationID令牌中的aud值是否等于应用程序的客户端ID。
  4. validationID令牌的到期时间(exp)是否未通过。
  5. 如果您在请求中传递了hd参数,请validationID令牌是否具有与您的G Suite托管域匹配的高清版权声明。

有一个关于如何在这里validation它们的官方示例项目。 很遗憾,我们尚未将此添加到Google .Net客户端库中。 它已被记录为一个问题

所以,我发现,因为OpenIDConnect规范有一个/.well-known/ url,其中包含validation令牌所需的信息。 这包括访问签名的公钥。 JWT中间件形成来自权威机构的.well-已知url,检索信息,然后继续自行validation。

这个问题的简短回答是validation已经在中间件中发生,没有什么可做的了。