我正在尝试将谷歌课堂api用于django项目。为此,我使用了oauth2.0,它可以在授权之前工作。但是当它重定向并调用 oauth2回调函数时,它会在 flow.fetch_token(( 中出现错误。
错误是 - MismatchingStateError at/google-class/oauth2callback/(mismatching_state(CSRF警告!请求和响应的状态不相等。
我该如何解决这个问题?
我按照这里的指示 - https://developers.google.com/identity/protocols/OAuth2WebServer#creatingcred
网址 -
path('profile/',views.profile, name='profile'),
path('google-class/',views.profile_g, name='profile_g'),
path('piazza/',views.profile_p, name='profile_p'),
path('google-class/oauth2callback/', views.oauth2callback, name='oauth2callback'),
在 views.py
def profile_g(request):
if request.method =='POST':
if 'credentials' not in request.session:
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json', scopes=SCOPES)
flow.redirect_uri = 'http://127.0.0.1:8000/google-class/oauth2callback/'
authorization_url, state = flow.authorization_url(
access_type='offline',
prompt='consent',
include_granted_scopes='true')
request.session['state'] = state
some = state
print("/n" + "The state is =" + state + "/n")
return redirect(authorization_url)
else:
return render(request,'api/profile.html')
def oauth2callback(request):
state = request.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json', scopes=SCOPES, state=state)
flow.redirect_uri = 'http://127.0.0.1:8000/google-class/oauth2callback/'
authorization_response = request.get_full_path()
# print(request.get_full_path())
flow.fetch_token(authorization_response=authorization_response)
credentials = flow.credentials
request.session['credentials'] = credentials_to_dict(credentials)
if 'credentials' in request.session:
# Load credentials from the session.
credentials = google.oauth2.credentials.Credentials(
request.session['credentials'])
service = build(API_SERVICE_NAME,API_VERSION, credentials=credentials)
# Call the Classroom API
results = service.courses().list(pageSize=10).execute()
courses = results.get('courses', [])
if not courses:
print('No courses found.')
else:
print('Courses:')
for course in courses:
print(course['name'])
return render(request,'api/google-class.html')
我认为它会有所帮助 而不是 authorization_response=authorization_response 来获取令牌 您可以使用代码=代码获取令牌 它对我有用(
def oauth2callback(request):
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json', scopes=SCOPES, state=state)
flow.redirect_uri = 'http://127.0.0.1:8000/google- class/oauth2callback/'
code = request.GET['code']
#print(code)
token = flow.fetch_token(code=code)
print(token)