我在我的Android应用中使用oauth 2.0和混合流程进行谷歌登录https://developers.google.com/identity/sign-in/web/server-side-flow。我将一次授权代码放入android应用程序并通过postman将其发布到我的flask api中。当我在api中将flow.step2_exchange应用于这一次授权代码时,它给了我流量交换错误。我已经检查了到达api的auth代码与我在应用程序中获得的代码相同。我找不到错误的原因。
我的一次授权代码如下所示:4 / qXilPdy7xOVe5swCBlVRrxjuVu8zEzfcmidlooo7_ls
我的烧瓶api的代码片段:
# IMPORTS FOR THIS STEP
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
import httplib2
import json
from flask import make_response
import requests
app = Flask(__name__)
CLIENT_ID = json.loads(
open('client_secrets.json', 'r').read())['web']['client_id']
APPLICATION_NAME = "OAUTH_SERVER"
SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
# Add other requested scopes.
]
# Connect to Database and create database session
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
@app.route('/gconnect', methods=['POST'])
def gconnect():
request.get_data()
code = request.data.decode('utf-8')
print (code)
# Upgrade the authorization code into a credentials object
oauth_flow = flow_from_clientsecrets('client_secrets.json', scope = SCOPES)
oauth_flow.redirect_uri = 'postmessage'
try:
credentials = oauth_flow.step2_exchange(code)
if credentials is None:
print ("it is empty")
except FlowExchangeError:
response = make_response(
json.dumps('Failed to upgrade the authorization code.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
我的Api的client_secret.json名为OAUTH_SERVER,如下所示:
{"web":
{"client_id":"matches the one in console.apps.googleusercontent.com",
"project_id":"oauthapi",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"###########",
"redirect_uris["http://localhost:5000/gconnect","http://localhost:5000/"],
"javascript_origins":["http://localhost:5000"]}
}
答案 0 :(得分:2)
我认为这是来自Udacity课程 - 身份验证&授权。请检查login.html是否包含正确的data-clientid值。我有同样的问题,因为复制后忘了改变我的。
答案 1 :(得分:0)
我认为你需要改变
# Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope = SCOPES) oauth_flow.redirect_uri = 'postmessage' try: credentials = oauth_flow.step2_exchange(code) if credentials is None: print ("it is empty") except FlowExchangeError:
到
try:
# Upgrade the authorization code into a credentials object
oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
oauth_flow.redirect_uri = 'postmessage'
credentials = oauth_flow.step2_exchange(code)
except FlowExchangeError: