我正在尝试在Django中构建一个Web应用程序,该应用程序要求用户使用Google Calendar API管理日历。我正在按照https://developers.google.com/identity/protocols/OAuth2WebServer中所述的步骤进行操作,但使用的是Django而不是Flask。
到目前为止,我已经编写了一个名为google_calendar()
的视图,该视图获取授权URL并重定向到该视图:
from django.conf import settings
from django.shortcuts import redirect
import google.oauth2.credentials
import google_auth_oauthlib.flow
# Client configuration for an OAuth 2.0 web server application
# (cf. https://developers.google.com/identity/protocols/OAuth2WebServer)
CLIENT_CONFIG = {'web': {
'client_id': settings.GOOGLE_CLIENT_ID,
'project_id': settings.GOOGLE_PROJECT_ID,
'auth_uri': 'https://accounts.google.com/o/oauth2/auth',
'token_uri': 'https://www.googleapis.com/oauth2/v3/token',
'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs',
'client_secret': settings.GOOGLE_CLIENT_SECRET,
'redirect_uris': settings.GOOGLE_REDIRECT_URIS,
'javascript_origins': settings.GOOGLE_JAVASCRIPT_ORIGINS}}
# This scope will allow the application to manage your calendars
SCOPES = ['https://www.googleapis.com/auth/calendar']
def get_authorization_url():
# Use the information in the client_secret.json to identify
# the application requesting authorization.
flow = google_auth_oauthlib.flow.Flow.from_client_config(
client_config=CLIENT_CONFIG,
scopes=SCOPES)
# Indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required.
flow.redirect_uri = 'http://localhost:8000'
# Generate URL for request to Google's OAuth 2.0 server.
# Use kwargs to set optional request parameters.
authorization_url, state = flow.authorization_url(
# Enable offline access so that you can refresh an access token without
# re-prompting the user for permission. Recommended for web server apps.
access_type='offline',
# Enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true')
return authorization_url, state
def google_calendar(request):
authorization_url, state = get_authorization_url()
response = redirect(to=authorization_url)
return response
但是,如果导航到此视图,则会收到400错误:
URL在这里不是很清晰,但是如果我将其复制粘贴到浏览器中,则会重定向到我想要的项目(即“ Cleo”)中另一个名为“ NPS Survey”的项目。然后,我收到一条错误消息,因为我已计划删除该项目:
我很确定我输入了Cleo项目的密钥,而不是NPS Survey的密钥。为什么要为错误的项目查找重定向URI?
答案 0 :(得分:1)
flow.redirect_uri = 'http://localhost:8000'
此uri表示用户成功通过身份验证后,Google IDP将重定向到。显然,您可以将其重定向到Google身份提供商中的http://localhost:8000
。这是“ NPS调查”。
您应该设置为flow.redirect_uri = 'http://yourhostip:8000'
。并在Google oauth端设置http://yourhostip:8000
关于重定向URL。