【问题标题】:Google PlayGamesAPI: How to validate ServerAuthCode in C#Google PlayGamesAPI:如何在 C# 中验证 ServerAuthCode
【发布时间】:2019-06-27 18:21:40
【问题描述】:

我开发了一个 Android 游戏,它成功地从 Google Play API 获取了 ServerAuthCode。我想将此 ServerAuthCode 发送到我用 C# 编写的自定义游戏服务器,并对其进行验证以对玩家进行身份验证。

Google 提供了一个 Java 文档(部分“将服务器身份验证代码交换为服务器上的访问令牌”):https://developers.google.com/games/services/android/offline-access 不幸的是,我无法将其用于 C#。

我有似乎包含所有 API 身份验证数据的 client_secret.json,我有 ServerAuthCode(这似乎是一个令牌)。

还有一个适用于 C# 的 NuGet 包,但它不包含上述文档中的所有类:https://www.nuget.org/packages/Google.Apis.AndroidPublisher.v3/

如何验证令牌?我也欢迎一个简单的 Postman 示例。

【问题讨论】:

    标签: c# google-play-services


    【解决方案1】:

    我通过反复试验找到了答案。需要注意的一件重要事情是服务器身份验证代码很快就会过期。如果您正在手动调试和复制粘贴,则在您运行代码之前,服务器验证码可能已经过期。在这种情况下,Google API 将“invalid_grant”作为错误返回,这对我来说是一种误导。

    在我的示例解决方案中,您需要在项目中有一个文件“client_secret.json”,该文件在构建时复制到输出目录(文件属性->“构建操作”=“内容”,“复制到输出目录" = "始终复制")。

    您从 Google API 控制台获取您的 client_secret.json 文件(https://console.developers.google.com/apis/credentials?project=,单击项目右侧“OAuth 2.0-Client-IDs”下的下载图标)。

    重要提示:重定向 url 必须与项目中配置的重定向 url 匹配。对我来说,它只是空的,所以只需使用一个空字符串。

    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Auth.OAuth2.Requests;
    using System;
    using System.IO;
    using System.Reflection;
    using System.Text;
    
    namespace GoogleApiTest
    {
        // Source: https://developers.google.com/identity/sign-in/android/offline-access
        class Program
        {
            static void Main(string[] args)
            {
                var authCode = "YOUR_FRESH_SERVER_AUTH_CODE";
    
                var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"client_secret.json");
                var config = File.ReadAllText(path, Encoding.UTF8);
    
                GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(new FileStream(path, FileMode.Open));
    
                var request = new AuthorizationCodeTokenRequest()
                {
                    ClientId = clientSecrets.Secrets.ClientId,
                    ClientSecret = clientSecrets.Secrets.ClientSecret,
                    RedirectUri = "",
                    Code = authCode,
                    GrantType = "authorization_code"
                };
    
                var tokenResponse = request.ExecuteAsync(new System.Net.Http.HttpClient(), "https://www.googleapis.com/oauth2/v4/token", new System.Threading.CancellationToken(), Google.Apis.Util.SystemClock.Default).GetAwaiter().GetResult();
    
                Console.ReadLine();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-14
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      相关资源
      最近更新 更多