Google SignIn получить токен доступа в веб-приложении - PullRequest
3 голосов
/ 23 сентября 2019

В моем веб-приложении (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 голосов
/ 23 сентября 2019

Я нашел решение с небольшой модификацией следующего ответа: 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

...