简体   繁体   English

如何获取 Google oauth2 刷新令牌?

[英]How to obtain a Google oauth2 refresh token?

The following code uses the Google oauth2 mechanism to sign in a user.以下代码使用 Google oauth2 机制来登录用户。 We need to process updates to the user's calendar while the user is offline, so we ultimately need the 'refresh token'.我们需要在用户离线时处理用户日历的更新,因此我们最终需要“刷新令牌”。 Does the result from grantOfflineAccess() return the refresh token (below, I can see that response.code holds a value that might be the refresh token)? grantOfflineAccess() 的结果是否返回刷新令牌(在下面,我可以看到 response.code 包含一个可能是刷新令牌的值)?

How can I get a refresh token that can be used (server side) to create new access keys for offline access to a user's Google calendar?如何获取可用于(服务器端)创建新访问密钥以离线访问用户 Google 日历的刷新令牌?

在此处输入图片说明

<script type="text/javascript">
    function handleClientLoad() {
        gapi.load('client:auth2', initClient);
    }

    function initClient() {
        gapi.client.init({
            apiKey: 'MY_API_KEY',
            clientId: 'MY_CLIENT_ID.apps.googleusercontent.com',
            discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
            scope: 'https://www.googleapis.com/auth/calendar'
        }).then(function () {
            var GoogleAuth = gapi.auth2.getAuthInstance();
            GoogleAuth.signIn();
            GoogleAuth.grantOfflineAccess().then(function (response) {
                var refresh_token = response.code;
            });
        });
    }

</script>

<script async defer src="https://apis.google.com/js/api.js"
        onload="this.onload=function(){};handleClientLoad()"
        onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

There is a reason why you are having a problem getting a refresh token out of JavaScript.从 JavaScript 获取刷新令牌时遇到问题是有原因的。 That reason being that it's not possible.那是因为这是不可能的。

JavaScript is a client side programming language, for it to work you would have to have your client id and client secret embedded in the code along with the refresh token . JavaScript 是一种客户端编程语言,要使其工作,您必须将您的客户端 ID 和客户端密码与刷新令牌一起嵌入代码中。 This would be visible to anyone who did a view source on the web page.这对于在网页上查看源代码的任何人都是可见的。

I think you realize why that's probably a bad idea.我想你明白为什么这可能是个坏主意。 The main issue is that gapi won't return it the library just doesn't have that ability ( not that I have tried in raw JavaScript to see if the OAuth server would return it if I asked nicely ).主要问题是gapi不会返回它,库只是没有这种能力(不是我尝试在原始 JavaScript 中查看 OAuth 服务器是否会在我问得好时返回它)。

You will need to switch to some server side language.您将需要切换到某种服务器端语言。 I have heard that this can be done with Node.js, but haven't tried myself.我听说这可以用 Node.js 来完成,但我自己没有尝试过。 And Java, PHP, Python are all valid options too. Java、PHP、Python 也是有效的选择。

Based from this post , you should include the specific scopes in your requests.根据这篇文章,您应该在请求中包含特定范围 Your client configuration should have $client->setAccessType("offline");你的客户端配置应该有$client->setAccessType("offline"); and $client->setApprovalPrompt("force");$client->setApprovalPrompt("force"); . .

After allowing access, you will be returned an access code that you can exchange for an access token.允许访问后,您将收到一个访问代码,您可以用它来交换访问令牌。 The access token returned is the one you need to save in a database.返回的访问令牌是您需要保存在数据库中的令牌。 Later on, if the user needs to use the calendar service, you simply use the access token you already saved.稍后,如果用户需要使用日历服务,您只需使用您已经保存的访问令牌。

Here's a sample code:这是一个示例代码:

 /* * @$accessToken - json encoded array (access token saved to database) */ $client = new Google_Client(); $client->setAuthConfig("client_secret.json"); $client->addScope("https://www.googleapis.com/auth/calendar"); $_SESSION["access_token"] = json_decode($accessToken, true); $client->setAccessToken($_SESSION['access_token']); $service = new Google_Service_Calendar($client); //REST OF THE PROCESS HERE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM