我正在使用带有混合流程的 oauth 2.0 进行谷歌登录 https://developers.google.com/identity/sign-in/web/server-side-flow在我的 Android 应用程序中。我将一次性授权码获取到 android 应用程序中,并通过 postman 将其发布到我的 flask api .当我将 flow.step2_exchange 应用到 api 中的这个一次性授权代码时,它给我流交换错误。我已经检查了到达 api 的授权代码与我在我的应用程序中获得的授权代码相同。我找不到错误的原因。
我的一次性授权代码如下所示:4/qXilPdy7xOVe5swCBlVRrxjuVu8zEzfcmidlooo7_ls
我的 flask api 的代码 fragment :
# 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"]}
}
最佳答案
据我所知,这是来自 Udacity 类(class) - 身份验证和授权。请检查 login.html 是否包含正确的 data-clientid 值。我遇到了同样的问题,因为在复制时忘记用我的更改它。
关于android - 401 Unauthorized error.将授权码升级为凭证对象失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40063448/