存储来自Google API的OAuth 2令牌以供将来请求

时间:2018-11-22 11:59:07

标签: javascript google-api google-calendar-api google-oauth google-oauth2

我可以使用文档和示例代码(来自Authorizing and Making Authorized Requests)授权并向Google API发出授权请求:

<html>
<head></head>
<body>
    <script type="text/javascript">
    function handleClientLoad() {
        // Loads the client library and the auth2 library together for efficiency.
        // Loading the auth2 library is optional here since `gapi.client.init` function will load
        // it if not already loaded. Loading it upfront can save one network request.
        gapi.load('client:auth2', initClient);
    }

    function initClient() {
        // Initialize the client with API key and People API, and initialize OAuth with an
        // OAuth 2.0 client ID and scopes (space delimited string) to request access.
        gapi.client.init({
            apiKey: 'YOUR_API_KEY',
            discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
            clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
            scope: 'profile'
        }).then(function () {
        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

        // Handle the initial sign-in state.
        updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
        });
    }

    function updateSigninStatus(isSignedIn) {
        // When signin status changes, this function is called.
        // If the signin status is changed to signedIn, we make an API call.
        if (isSignedIn) {
        makeApiCall();
        }
    }

    function handleSignInClick(event) {
        // Ideally the button should only show up after gapi.client.init finishes, so that this
        // handler won't be called before OAuth is initialized.
        gapi.auth2.getAuthInstance().signIn();
    }

    function handleSignOutClick(event) {
        gapi.auth2.getAuthInstance().signOut();
    }

    function makeApiCall() {
        // Make an API call to the People API, and print the user's given name.
        gapi.client.people.people.get({
        'resourceName': 'people/me',
        'requestMask.includeField': 'person.names'
        }).then(function(response) {
        console.log('Hello, ' + response.result.names[0].givenName);
        }, function(reason) {
        console.log('Error: ' + reason.result.error.message);
        });
    }
    </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>
    <button id="signin-button" onclick="handleSignInClick()">Sign In</button>
    <button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
</body>
</html>

但是,我只能在会话仍存在的情况下发出请求。我想要的是将令牌存储在数据库中,然后使用此令牌进行请求。

最终,我希望有一个用户设置页面,用户可以在该页面上同意该应用程序(即链接/取消链接Google API),以便他们始终可以查看自己是否已获得授权以及何时需要更新访问令牌。我希望它的行为类似于用户通常可以在其帐户设置中链接/取消链接“使用Facebook / Google / GitHub登录”。

但是我没有在Google API文档中如何检索令牌以及如何基于短暂令牌进行请求。

我该如何完成? Google API文档中有这样做的例子吗?

1 个答案:

答案 0 :(得分:0)

您看到的令牌是访问令牌。访问令牌是短暂的令牌,可让您访问用户数据。您需要的是刷新令牌,当您的访问令牌过期时(一个小时后),它将使您能够请求新的访问令牌。

您不能在客户端应用程序中使用刷新令牌。您将需要切换到服务器端解决方案,例如node.js,php或python。

您可以详细了解here