Google登录在Web App中获取访问令牌

时间:2019-09-23 08:11:22

标签: angular google-cloud-platform refresh-token google-cloud-print

在我的Web应用程序(FE:Angular,BE:Flask)中,我要求用户使用Google登录并将刷新令牌保存在数据库中。

浏览google文档后,我了解到只能在服务器端应用程序中获取刷新令牌。但是,文档中指定的代码似乎无效。 参考:https://developers.google.com/identity/sign-in/web/server-side-flow

我在第7步中遇到错误,https://developers.google.com/identity/sign-in/web/server-side-flow#step_7_exchange_the_authorization_code_for_an_access_token

from apiclient import discovery
import httplib2
from oauth2client import client

# (Receive auth_code by HTTPS POST)


# If this request does not have `X-Requested-With` header, this could be a CSRF
if not request.headers.get('X-Requested-With'):
    abort(403)

# Set path to the Web application client_secret_*.json file you downloaded from the
# Google API Console: https://console.developers.google.com/apis/credentials
CLIENT_SECRET_FILE = '/path/to/client_secret.json'

# Exchange auth code for access token, refresh token, and ID token
credentials = client.credentials_from_clientsecrets_and_code(
    CLIENT_SECRET_FILE,
    ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
    auth_code)

# Call Google API
http_auth = credentials.authorize(httplib2.Http())
drive_service = discovery.build('drive', 'v3', http=http_auth)
appfolder = drive_service.files().get(fileId='appfolder').execute()

# Get profile info from ID token
userid = credentials.id_token['sub']
email = credentials.id_token['email']

1 个答案:

答案 0 :(得分:0)

我找到了解决方案, 略微修改了以下响应,https://stackoverflow.com/a/50616780/11997783

更改登录功能自

this.auth2.signIn().then(user => {})

signIn(): void {
this.auth2.grantOfflineAccess().then((resp) => {});

使用 grantOfflineAccess(),我们将能够获得授权码。

POST the Authorization code to https://oauth2.googleapis.com/token with parameters 
code: <authorization-code> ,
client_id: <project-client-id>, 
client_secret: <project-client-secret>, 
redirect_uri: <should be uri of the FE>, 
grant_type: authorization_code

其他参考:https://developers.google.com/identity/sign-in/web/reference#gapiauth2clientconfig