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

时间:2015-08-27 21:56:50

标签: android asp.net-mvc authentication asp.net-web-api google-oauth

过去两天我一直在抨击我的大脑,试图了解如何使用内置于ASP.NET的WebAPI 2中的身份验证,使用Google作为外部身份验证,而不熟悉OAuth 2 ,我很失落。我已按照this tutorial设置我的Android客户端上的登录按钮,然后发送" idToken"到Web API。关于将Google设置为外部登录信息,我也按照此(现已过时)tutorial进行了操作。

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

我发现这个SO answer表示要从/ 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 Client library通过Google API进行授权。

  5. 更新2 :我还在努力获取此AuthenticationFilter实施。事情似乎在这一点上进展顺利,但我却陷入了一些困境。我一直在使用this example来获取令牌验证码,并this tutorial来获取AuthenticationFilter代码。结果是两者的混合。我会在这里作为答案发布完毕。

    以下是我目前的问题:

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

    2. 我仍然不清楚这是什么正确的流程。我目前正在使用身份验证标头使用自定义方案传递我的id_token字符串:" goog_id_token"。客户端必须使用此自定义AuthenticationFilter为API上调用的每个方法发送其id_token。我不知道在专业环境中通常会如何做到这一点。这似乎是一个很常见的用例,会有大量有关它的信息,但我还没有看到它。我已经看到了正常的OAuth2流程,并且因为我只使用了ID令牌,而不是访问令牌,所以在ID令牌应该用于什么时,我会丢失一个ID令牌。流,以及它应该存在于HTTP数据包中的位置。因为我不了解这些事情,所以我一直在努力弥补这一切。

1 个答案:

答案 0 :(得分: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();

客户端添加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智能感知来查找所有查找函数及其覆盖。我从我的数据库中的Identity Framework创建的表中注意到有一个名为UserLogin的行,其行包含提供者,提供者密钥和用户FK。 FindAsync()采用UserLoginInfo对象,该对象仅包含提供程序字符串和提供程序键。我预感到这两件事现在有关系了。我还记得,令牌格式中有一个字段,其中包含一个以字符开头的字段,该字段以1开头。

validatedToken似乎基本上是空的,不是null,而是一个空的SecurityToken。这就是我使用token代替validatedToken的原因。我认为这一定有问题,但由于cp不是null,这是对验证失败的有效检查,因此原始令牌有效是足够的。

                    // 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());
            }
        }
    }        
}

其余的只是异常捕捉。

感谢您查看此信息。希望您可以查看我的源代码,看看哪些组件来自哪个代码库。

相关问题