如何在 Google API 中使用 Web 应用程序生成的令牌填充本机应用程序凭据?

How can I fill native app credentials with web app generated token in Google API?

我正在做一些基于网络的应用程序,它显示来自数据库条目的用户日历。在此网络应用程序中,用户可以通过 JavaScript 库验证其 Google 日历帐户。然后我想与我的桌面服务共享此访问权限。桌面服务是用 C# 编写的。

有谁知道如何使用以下代码在 C# 中填写 CalendarService class?

Javascript:

function auth() {
            var config = {
                'client_id': "myID",
                'scope': "https://www.googleapis.com/auth/calendar"
            };
            gapi.auth.authorize(config, function () {
                console.log('login complete');
                console.log(gapi.auth.getToken());
            });
        }

然后Windows服务中有我的C#代码

var tokenResponse = new TokenResponse
{
        AccessToken = tokenCopiedFromJavascriptObject,
        Issued = propertyCopiedFromJavascriptObject,
        TokenType = "Bearer",
        Scope = CalendarService.Scope.Calendar,
        RefreshToken = "3600"
};

var authorizationCodeFlowInitializer = new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets()
            {
                ClientId = myIdForDesktopApp,
                ClientSecret = ClientSecretForDestopApp
            },
            Scopes = new[] { CalendarService.Scope.Calendar },
            Clock = Google.Apis.Util.SystemClock.Default
        };
        var authorizationCodeFlow = new GoogleAuthorizationCodeFlow(authorizationCodeFlowInitializer);
        _credentials = new UserCredential(authorizationCodeFlow, _calendarId, tokenResponse);

        _service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = _credentials,
            ApplicationName = "Fast and Easy Reservation System"
        });
        const string meeting = "Some fancy meeting";
        var e = _service.Events.QuickAdd("primary", meeting).Execute();
    }

有没有希望让它发挥作用?例如,我的 Google API 项目中有 2 个应用程序(网络和桌面)。这些都在一个项目中,所以我认为它应该作为一个混合应用程序工作,它们应该共享一个授权令牌。

JS auth 函数返回的对象具有以下属性: access_token client_id expires_at expires_in issued_at response_type 范围 token_type

我在 ASP.NET MVC 应用程序中制作了 Controler 来处理 Javascript 代码并将令牌发送到我的数据库。 为了避免不兼容的应用程序类型(Web 和本机),我的 Windows 服务使用来自 Web 类型应用程序的 client_secrets.json 文件。为了精确控制应用程序流并以某种方式欺骗本机服务是 Web 应用程序,我只从 client_secrets.json(Web)加载了 client_id 和 client_secret。

            var flow = new GoogleAuthorizationCodeFlow(
            new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets()
                {
                    ClientId = "some-numbersAndLettersxxxxxxxxxx.apps.googleusercontent.com",
                    ClientSecret = "xxxxxxxxxxxxxx"
                }
            });

然后,我在我的应用程序中从数据库加载令牌并分配它。

var token = new TokenResponse
        {
            RefreshToken = "ya29.UAH2llQasSADfga32fWay3aqi1pb0AUwAWy_WzbPNyNkYCRPhe5_zBbEG94TZafV8pBMHzC8Q"
        };

在准备好流程和令牌后,我能够创建凭据对象。

var credential = new UserCredential(flow, clientId, token);

现在,本机应用伪装成 Web 应用程序,无需额外的同意屏幕即可访问所有用户数据。