使用Google身份验证从Android客户端使用WebAPI2网站

Lav*_*Hot 6 authentication asp.net-mvc android asp.net-web-api google-oauth

在过去的两天里,我一直在绞尽脑汁,试图了解如何使用内置于Google.NET的ASP.NET WebAPI 2中的身份验证作为外部身份验证,而对OAuth 2并不熟悉,我很失落。我已经按照本教程设置了Android客户端上的登录按钮,并将“ idToken”发送到Web API。我还按照本教程(现在已过时)中的说明将Google设置为外部登录名。

当我尝试发送它{"error":"unsupported_grant_type"}作为响应时,就会发生问题。其他一些教程使我相信,mysite.com / token的POST不包含正确的数据。这意味着我要么在客户端上错误地构建了请求,要么以某种方式在后端上不正确地处理了请求,将其发送到错误的url,或者我在做其他完全错误的事情。

我找到了这个答案,说是从/ api / Accounts / ExternalLogins获取URL,但是登录按钮已经给了我提供给我的访问令牌(如果我正确理解的话)。

如果有人可以帮助我解决从头到尾的确切流程,那就太好了。

更新:好的,这是自问这个问题以来我学到的一些东西。

  1. website.com/token URI是WebAPI2模板中内置OAuth服务器的重定向。这对于此特定问题没有用。

  2. id_token是已编码的JWT令牌。

  3. website.com/signin-google URI是正常Google登录名的重定向,但不接受这些令牌。

  4. 我可能必须编写自己的AuthenticationFilter,它使用Google客户端库通过Google API进行授权。

更新2:我仍在努力获取AuthenticationFilter实现。此时一切似乎进展顺利,但我在某些事情上陷于困境。我一直在使用此示例获取令牌验证代码,并在本教程中获取AuthenticationFilter代码。结果是两者的混合。完成后,我会将其发布在此处作为答案。

这是我目前的问题:

  1. 产生一个IPrincipal作为输出。验证示例创建了ClaimPrincipal,但是AuthenticationFilter示例代码使用UserManager将用户名与现有用户进行匹配,并返回该主体。验证示例中创建的ClaimsPrincipal不会直接与现有用户自动关联,因此我需要尝试将声明的某些元素与现有用户进行匹配。那我该怎么做呢?

  2. 对于什么合适的流程,我还是个不完整的想法。我目前正在使用Authentication标头通过自定义方案“ goog_id_token”传递我的id_token字符串。客户端必须使用此自定义AuthenticationFilter为API上调用的每个方法发送其id_token。我不知道通常如何在专业环境中完成此操作。似乎很常见的用例是会有大量的信息,但是我还没有看到。我已经看到了正常的OAuth2流程,由于我仅使用一个ID令牌,而不使用访问令牌,所以我对于应该使用的ID令牌,它属于流的位置以及使用它的方式有点困惑应该放在HTTP数据包中的位置。而且因为我不知道这些事情,所以我一直在努力地进行弥补。

Lav*_*Hot 1

哇,我做到了。我想到了。我……我简直不敢相信。

正如我的问题更新 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();
Run Code Online (Sandbox Code Playgroud)

客户端添加授权标头字段,其中方案后跟一个空格,然后是 id 令牌。它看起来像Authorization: id-token-goog IaMS0m3.Tok3nteXt...。按照谷歌文档中的规定将 ID 令牌放入正文中在此过滤器中没有任何意义,因此我决定将其放入标头中。由于某些原因,很难从 HTTP 数据包中提取自定义标头,因此我决定使用带有自定义方案的授权标头,后跟 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;
    }
Run Code Online (Sandbox Code Playgroud)

过滤器的全部要点是忽略过滤器不管理的请求(不熟悉的身份验证方案等),并对它应该管理的请求做出判断。允许有效的身份验证传递到下游 AuthorizeFilter 或直接传递到控制器。

我制定了“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)
            };
Run Code Online (Sandbox Code Playgroud)

这与 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>();
Run Code Online (Sandbox Code Playgroud)

从 OWIN 上下文获取用户管理器。我必须在context智能感知中进行挖掘,直到找到为止GetOwinCOntext(),然后发现我必须添加using Microsoft.Aspnet.Identity.Owin;才能添加包含该方法的部分类GetUserManager<>()

                    ApplicationUser au = 
                        await um
                            .FindAsync(
                                new UserLoginInfo(
                                    "Google", 
                                    token.Subject)
                            );
Run Code Online (Sandbox Code Playgroud)

这是我必须解决的最后一件事。同样,我必须深入研究umIntellisense 才能找到所有 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;
Run Code Online (Sandbox Code Playgroud)

在这里,我必须创建一个新的 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());
            }
        }
    }        
}
Run Code Online (Sandbox Code Playgroud)

剩下的只是异常捕获。

感谢您查看此内容。希望您可以查看我的来源并了解哪些组件来自哪个代码库。