这两天我一直在绞尽脑汁,试图了解如何使用 ASP.NET 的 WebAPI 2 中内置的身份验证,使用 Google 作为外部身份验证,而不熟悉 OAuth 2,我很迷茫.我关注了this tutorial在我的 Android 客户端上设置登录按钮并将“idToken”发送到 Web API。我也关注了这个(现在已经过时了)tutorial关于将 Google 设置为外部登录。
当我尝试发送它时出现问题,我收到 {"error":"unsupported_grant_type"}
作为响应。其他一些教程让我相信 mysite.com/token 的 POST 不包含正确的数据。这意味着我要么在客户端错误地构建请求,要么在后端以某种方式错误地处理它,要么将它发送到错误的 url,要么我在做其他完全错误的事情。
我找到了这个 SO answer它说要从/api/Accounts/ExternalLogins 获取 URL,但登录按钮已经为我提供了将提供给我的访问 token (如果我理解正确的话)。
如果有人可以帮助我了解从头到尾的确切流程,那就太棒了。
更新:好的,下面是我提出这个问题后学到的一些东西。
website.com/token URI 是 WebAPI2 模板中内置 OAuth 服务器的重定向。这对于这个特定问题没有用。
id_token 是一个编码的 JWT token 。
website.com/signin-google URI 是普通 Google 登录的重定向,但不接受这些 token 。
我可能需要自己写 AuthenticationFilter使用 Google Client library通过 Google API 授权。
更新 2:我仍在努力获取此 AuthenticationFilter 实现。在这一点上事情似乎进展顺利,但我在某些事情上遇到了困难。我一直在使用 this example获取token验证码,this tutorial获取 AuthenticationFilter 代码。结果是两者的混合。完成后,我会将其作为答案发布在这里。
这是我目前的问题:
生成 IPrincipal 作为输出。验证示例生成 ClaimPrincipal,但 AuthenticationFilter 示例代码使用 UserManager 将用户名与现有用户匹配并返回该主体。验证示例中直接创建的 ClaimsPrincipal 不会与现有用户自动关联,因此我需要尝试将声明的某些元素与现有用户匹配。那我该怎么做呢?
对于什么是正确的流程,我仍然不完全了解。我目前正在使用身份验证 header 通过自定义方案传递我的 id_token 字符串:“goog_id_token”。客户端必须为使用此自定义 AuthenticationFilter 在 API 上调用的每个方法发送其 id_token。我不知道这在专业环境中通常是如何完成的。这似乎是一个足够常见的用例,因此会有大量关于它的信息,但我还没有看到它。我已经看到了正常的 OAuth2 流程,并且由于我只使用了 ID token ,而不是访问 token ,所以我对 ID token 应该用于什么,它在流程中的位置,以及它应该位于 HTTP 数据包中的位置。因为我不知道这些事情,所以我一直在编造它。
最佳答案
哇,我做到了。我想到了。我……我简直不敢相信。
正如我在问题更新 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();
客户端添加授权 header 字段,方案后跟一个空格,然后是 id token 。它看起来像 Authorization: id-token-goog IaMS0m3.Tok3nteXt...
.按照 google 文档中的说明将 ID token 放入正文中,在此过滤器中没有任何意义,因此我决定将其放入 header 中。出于某种原因,很难从 HTTP 数据包中提取自定义 header ,所以我决定使用带有自定义方案的授权 header ,后跟 ID token 。
// 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( token 字符串的解析、解码版本)和设置验证参数方面发挥了一些作用。我不确定为什么这个部分的底部在它自己的语句 block 中,但它与 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
智能感知,直到我找到 GetOwinCOntext()
,然后发现我必须添加 using Microsoft.Aspnet.Identity.Owin;
为了添加包含方法 GetUserManager<>()
的部分类.
ApplicationUser au =
await um
.FindAsync(
new UserLoginInfo(
"Google",
token.Subject)
);
这是我必须解决的最后一件事。同样,我不得不深入挖掘 um
用于查找所有 Find 函数及其覆盖的 Intellisense。我从我的数据库中身份框架创建的表中注意到,有一个名为 UserLogin 的表,其行包含一个提供者、一个提供者 key 和一个用户 FK。 FindAsync()
需要 UserLoginInfo
对象,它只包含一个提供者字符串和一个提供者键。我有一种预感,这两件事现在是相关的。我还记得 token 格式中有一个字段,其中包含一个看起来很关键的字段,它是一个以 1 开头的长数字。
validatedToken
似乎基本上是空的,不是null,而是一个空的SecurityToken。这就是我使用 token
的原因而不是 validatedToken
.我想这一定有问题,但自从 cp
不为空,这是对验证失败的有效检查,这足以证明原始 token 有效。
// 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());
}
}
}
}
剩下的只是异常捕获。
感谢您查看此内容。希望您可以查看我的来源并查看哪些组件来自哪个代码库。
关于android - 使用 Google 身份验证从 Android 客户端使用 WebAPI2 站点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260105/