我正在尝试在谷歌应用程序引擎 python 3 灵活环境上创建 Flask Web 应用程序,并在自定义域上使用 oauth2 身份验证。
所以,问题如下:
1)我已将自定义域添加到我的项目中,并将 SSL 添加到该自定义域。在谷歌云控制台中,一切似乎都很好,但 SSL 未在我的自定义域上显示/工作。
也许问题出在我的调度文件中?
dispatch:
- url: 'mycustomdomain.com/'
service: default
- url: 'www.mycustomdomain.com/'
service: default
2)尽管https://[project-id].appspot.com上有SSL,但我仍无法登录。按“使用 Google 登录”后,我将重定向到/authorize,在那里我选择要登录的帐户。之后重定向到/oauth2callback,https 神秘地更改为 http,我无法登录,并出现以下错误 InsecureTransportError: (insecure_transport) OAuth 2 必须使用 https。
Python授权:
@app.route('/authorize')
def authorize():
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true')
flask.session['state'] = state
return flask.redirect(authorization_url)
Python oauth2callback:
@app.route('/oauth2callback')
def oauth2callback():
state = flask.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)
authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)
credentials = flow.credentials
flask.session['credentials'] = credentials_to_dict(credentials)
session = flow.authorized_session()
flask.session['username_output'] = session.get(
'https://www.googleapis.com/userinfo/v2/me').json()
return flask.redirect(flask.url_for('map'))
在本地测试时,我使用os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
并且在本地它工作得很好
有什么建议吗? p>
解决方案
问题已解决 -
1)我忘记将 SSL 证书添加到域(托管域的位置),这就是 SSL 不显示的原因。我知道,这是一个蹩脚的错误。
2)首先,我用SSLify为flask强制使用SSL,但这并没有解决问题,在下面的行中
authorization_response = flask.request.url
无论如何,这行代码给了我http://,我尝试将我能在flask.url_for(_scheme='https')中找到的每个方案更改为https,但这也没有帮助,所以现在,我的解决方法是
authorization_response = authorization_response.replace('http', 'https')
我知道,这不是最好的解决方案,但它有效。
最佳答案
我也遇到了这个问题,发现问题源于 authorization_response =flask.request.url
因为该 URL 默认为 HTTP 而不是 HTTPS。
我的黑客解决方案是运行快速正则表达式替换并强制 URL 为 HTTPS:
import re
....
authorization_response = request.url
new_auth = re.sub(
"http:",
"https:",
authorization_response
)
flow.fetch_new_token(new_auth)
当然有更好的方法来实现这一点,但它确实有效。
关于python - Google App Engine Flask SSL 和 OAuth2 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49071504/