哇,我做到了。我想到了。我……我不敢相信。
正如我在问题 Update 2 中提到的,此代码是由 Google 的官方 API C# 示例和 Microsoft 的 Custom AuthenticationFilter 教程和代码示例组装而成的。我将在此处粘贴 AuthorizeAsync() 并检查每个代码块的作用。如果您认为您发现了问题,请随时提出。
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
bool token_valid = false;
HttpRequestMessage request = context.Request;
// 1. Look for credentials in the request
//Trace.TraceInformation(request.ToString());
string idToken = request.Headers.Authorization.Parameter.ToString();
客户端添加 Authorization 标头字段,其方案后跟一个空格,后跟 id 令牌。它看起来像Authorization: id-token-goog IaMS0m3.Tok3nteXt...。将 ID 令牌放入 google 文档中给出的正文中在此过滤器中没有任何意义,因此我决定将其放入标题中。由于某种原因,很难从 HTTP 数据包中提取自定义标头,因此我决定使用 Authorization 标头和自定义方案,后跟 ID 令牌。
// 2. If there are no credentials, do nothing.
if (idToken == null)
{
Trace.TraceInformation("No credentials.");
return;
}
// 3. If there are credentials, but the filter does not recognize
// the authentication scheme, do nothing.
if (request.Headers.Authorization.Scheme != "id-token-goog")
// Replace this with a more succinct Scheme title.
{
Trace.TraceInformation("Bad scheme.");
return;
}
过滤器的全部意义在于忽略过滤器不管理的请求(不熟悉的身份验证方案等),并对它应该管理的请求做出判断。允许有效的身份验证传递给下游 AuthorizeFilter 或直接传递给 Controller。
我制定了“id-token-goog”方案,因为我不知道这个用例是否存在现有方案。如果有,请有人告诉我,我会修复它。我想目前这并不重要,只要我的客户都知道这个方案。
// 4. If there are credentials that the filter understands, try to validate them.
if (idToken != null)
{
JwtSecurityToken token = new JwtSecurityToken(idToken);
JwtSecurityTokenHandler jsth = new JwtSecurityTokenHandler();
// Configure validation
Byte[][] certBytes = getCertBytes();
Dictionary<String, X509Certificate2> certificates =
new Dictionary<String, X509Certificate2>();
for (int i = 0; i < certBytes.Length; i++)
{
X509Certificate2 certificate =
new X509Certificate2(certBytes[i]);
certificates.Add(certificate.Thumbprint, certificate);
}
{
// Set up token validation
TokenValidationParameters tvp = new TokenValidationParameters()
{
ValidateActor = false, // check the profile ID
ValidateAudience =
(CLIENT_ID != ConfigurationManager
.AppSettings["GoogClientID"]), // check the client ID
ValidAudience = CLIENT_ID,
ValidateIssuer = true, // check token came from Google
ValidIssuer = "accounts.google.com",
ValidateIssuerSigningKey = true,
RequireSignedTokens = true,
CertificateValidator = X509CertificateValidator.None,
IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
{
return identifier.Select(x =>
{
// TODO: Consider returning null here if you have case sensitive JWTs.
/*if (!certificates.ContainsKey(x.Id))
{
return new X509SecurityKey(certificates[x.Id]);
}*/
if (certificates.ContainsKey(x.Id.ToUpper()))
{
return new X509SecurityKey(certificates[x.Id.ToUpper()]);
}
return null;
}).First(x => x != null);
},
ValidateLifetime = true,
RequireExpirationTime = true,
ClockSkew = TimeSpan.FromHours(13)
};
这与 Google 示例没有任何变化。我几乎不知道它做了什么。这基本上在创建 JWTSecurityToken(令牌字符串的已解析、解码版本)和设置验证参数方面发挥了作用。我不确定为什么本节的底部位于它自己的语句块中,但它与 CLIENT_ID 和该比较有关。我不确定 CLIENT_ID 的值何时或为什么会改变,但显然这是必要的......
try
{
// Validate using the provider
SecurityToken validatedToken;
ClaimsPrincipal cp = jsth.ValidateToken(idToken, tvp, out validatedToken);
if (cp != null)
{
cancellationToken.ThrowIfCancellationRequested();
ApplicationUserManager um =
context
.Request
.GetOwinContext()
.GetUserManager<ApplicationUserManager>();
从 OWIN 上下文中获取用户管理器。我不得不在context intellisense 中挖掘,直到找到GetOwinCOntext(),然后发现我必须添加using Microsoft.Aspnet.Identity.Owin; 才能添加包含方法GetUserManager<>() 的部分类。
ApplicationUser au =
await um
.FindAsync(
new UserLoginInfo(
"Google",
token.Subject)
);
这是我必须解决的最后一件事。再一次,我不得不通过um Intellisense 来查找所有 Find 函数及其覆盖。我从我的数据库中的身份框架创建的表中注意到有一个称为 UserLogin 的表,其行包含一个提供程序、一个提供程序密钥和一个用户 FK。 FindAsync() 采用 UserLoginInfo 对象,该对象仅包含提供者字符串和提供者键。我有一种预感,这两件事现在是相关的。我还记得令牌格式中有一个字段,其中包含一个以 1 开头的长数字。
validatedToken 似乎基本上是空的,不是 null,而是一个空的 SecurityToken。这就是我使用token 而不是validatedToken 的原因。我认为这一定有问题,但由于cp 不为空,这是对验证失败的有效检查,因此原始令牌有效就足够了。
// If there is no user with those credentials, return
if (au == null)
{
return;
}
ClaimsIdentity identity =
await um
.ClaimsIdentityFactory
.CreateAsync(um, au, "Google");
context.Principal = new ClaimsPrincipal(identity);
token_valid = true;
在这里我必须创建一个新的 ClaimsPrincipal 因为上面在验证中创建的那个是空的(显然这是正确的)。猜测CreateAsync() 的第三个参数应该是什么。它似乎是这样工作的。
}
}
catch (Exception e)
{
// Multiple certificates are tested.
if (token_valid != true)
{
Trace.TraceInformation("Invalid ID Token.");
context.ErrorResult =
new AuthenticationFailureResult(
"Invalid ID Token.", request);
}
if (e.Message.IndexOf("The token is expired") > 0)
{
// TODO: Check current time in the exception for clock skew.
Trace.TraceInformation("The token is expired.");
context.ErrorResult =
new AuthenticationFailureResult(
"Token is expired.", request);
}
Trace.TraceError("Error occurred: " + e.ToString());
}
}
}
}
其余的只是异常捕获。
感谢您查看此内容。希望您可以查看我的资源并了解哪些组件来自哪个代码库。