我使用ASP.NET Core为Android客户端提供API。 Android以Google帐户登录,并将ID令牌JWT作为承载令牌传递给API。我有应用程序工作,它确实通过了身份验证检查,但我不认为它验证了令牌签名。
根据Google的文档,我可以调用此网址来执行此操作: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中间件验证签名?我已经接近放弃使用MS中间件并自行滚动。
答案 0 :(得分:30)
有几个不同的ways,您可以在其中验证服务器端ID令牌的完整性:
iss
个字段;主要优势(虽然我认为是一个小优势)我在这里看到的是,您可以最大限度地减少发送给Google的请求数量。https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
这是第二个看起来如何:
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<GoogleApiTokenInfo>(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
{
/// <summary>
/// The Issuer Identifier for the Issuer of the response. Always https://accounts.google.com or accounts.google.com for Google ID tokens.
/// </summary>
public string iss { get; set; }
/// <summary>
/// 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.
/// </summary>
public string at_hash { get; set; }
/// <summary>
/// Identifies the audience that this ID token is intended for. It must be one of the OAuth 2.0 client IDs of your application.
/// </summary>
public string aud { get; set; }
/// <summary>
/// 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.
/// </summary>
public string sub { get; set; }
/// <summary>
/// True if the user's e-mail address has been verified; otherwise false.
/// </summary>
public string email_verified { get; set; }
/// <summary>
/// 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.
/// </summary>
public string azp { get; set; }
/// <summary>
/// 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".
/// </summary>
public string email { get; set; }
/// <summary>
/// The time the ID token was issued, represented in Unix time (integer seconds).
/// </summary>
public string iat { get; set; }
/// <summary>
/// The time the ID token expires, represented in Unix time (integer seconds).
/// </summary>
public string exp { get; set; }
/// <summary>
/// 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.
/// </summary>
public string name { get; set; }
/// <summary>
/// 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.
/// </summary>
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; }
}
答案 1 :(得分:14)
根据此github issue,您现在可以使用GoogleJsonWebSignature.ValidateAsync
方法验证Google签名的JWT。只需将idToken
字符串传递给方法。
var validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken);
Assert.IsNotNull(validPayload);
如果它不是有效令牌,则会返回null
。
请注意,要使用此方法,您需要先安装Google.Apis.Auth nuget。
答案 2 :(得分:3)
Google在openId connect
的文档中说明出于调试目的,您可以使用Google的tokeninfo端点。假设您的ID令牌的值是XYZ123。
您不应该使用该端点来验证您的JWT。
验证ID令牌需要几个步骤:
有一个关于如何验证它们的官方示例项目here。很遗憾,我们尚未将此添加到Google .Net客户端库中。它已被记录为issue
答案 3 :(得分:2)
所以,我发现,因为OpenIDConnect规范有一个/.well-known/ url,其中包含验证令牌所需的信息。这包括访问签名的公钥。 JWT中间件形成来自权威机构的.well-已知url,检索信息,然后继续自行验证。
问题的简短回答是验证已经在中间件中进行,没有什么可做的了。
答案 4 :(得分:0)
private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}";
Public ProviderUserDetails ValidateGoogleToken(string providerToken)
{
var httpClient = new HttpClient();
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<GoogleApiTokenInfo>(response);
return new ProviderUserDetails
{
Email = googleApiTokenInfo.email,
FirstName = googleApiTokenInfo.given_name,
LastName = googleApiTokenInfo.family_name,
Locale = googleApiTokenInfo.locale,
Name = googleApiTokenInfo.name,
ProviderUserId = googleApiTokenInfo.sub
};
}
答案 5 :(得分:0)
我认为值得一提的是,您可以使用@Alexandru Marculescu答案进行身份验证,但是文档中有一条注释说明不要使用方法2。
Per the documentation under Calling the tokeninfo endpoint(已更改为https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123)
It is not suitable for use in production code as requests may be throttled or otherwise subject to intermittent errors.
推荐的验证idToken的方法是调用Google API客户端库。这就是我执行验证检查的方式
using Google.Apis.Auth;
...
public async Task<GoogleJsonWebSignature.Payload> ValidateIdTokenAndGetUserInfo(string idToken)
{
if (string.IsNullOrWhiteSpace(idToken))
{
return null;
}
try
{
return await GoogleJsonWebSignature.ValidateAsync(idToken);
}
catch (Exception exception)
{
_Logger.LogError(exception, $"Error calling ValidateIdToken in GoogleAuthenticateHttpClient");
return null;
}
}