1

我已经成功地使用谷歌登录库创建了一个谷歌登录按钮,请求额外的范围,但是我无法弄清楚如何将其转换为 API 请求。我正在使用googleUser.getAuthResponse().id_token并获取令牌,但我不确定如何将其转换为访问令牌以与我的 API 请求一起发送?

我使用的几乎就是文档中的内容:

    function onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();

    document.getElementById("acc").src = profile.getImageUrl();
    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
    console.log('Name: ' + profile.getName());
    console.log('Image URL: ' + profile.getImageUrl());
    console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
    
    var oAuthToken = googleUser.getAuthResponse().id_token
    }
4

1 回答 1

1

The ID Token returned by Google Sign-In is not accepted as a credential for any Google APIs. It is intended only for passing to your backend so you can securely identify the user there.

You need an Access Token to call Google APIs. The token can be retrieved in your onSignIn method with googleUser.getAuthResponse(true).access_token. This will only be present if you've requested scopes other than basic profile scopes, which you'd need for API access anyway.

Google Sign-In is built on top of GAPI. Once the user is signed-in, you can check gapi.auth2.getAuthInstance().isSignedIn.get() to verify the user is signed in, as far as GAPI is concerned. At this point, using GAPI to call Google APIs will attach credentials to the request to Google's servers.

于 2021-02-26T16:14:19.680 回答