开发Flask应用程序( Python3 / Heroku)供公司内部使用,并成功实施基于 brijieshb42’s article的Google登录(Oauth2),该登录使用requests_oauthlib.
研究表明,如果我在我的授权网址中传递参数“hd”(托管域名),它应该可以解决问题.例如.
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=OUR_CLIENT_ID&redirect_uri=https%3A%2F%2FOUR_APP.herokuapp.com%2Fconnect&scope=profile+email&state=STATE&安培; HD = our_google_apps_domain.com&安培; ACCESS_TYPE =离线
我的理解是,此参数应该提供客户端限制,并且仅允许来自我们的谷歌应用程序域(服务器端,我将在此之后处理!)的电子邮件登录,基于Google Documentation,this mailing list post和这些stackoverflow帖子:post1,post2.
但是,虽然我的代码生成了我上面粘贴的授权URL – 我仍然可以使用我的个人Gmail帐户登录(@ gmail.com vs @our apps domain.com).
任何人都可以解释为什么这不起作用?或者提供不同的方法?基本上更愿意阻止非员工登录.
我可以根据需要共享代码,但几乎粘贴了brijeshb42文章,基本上看起来像这样:
OAuth2Session(
OUR_CLIENT_ID,
redirect_uri=https://OUR_APP.herokuapp.com/connect,
scope=['profile', 'email']).authorization_url(
https://accounts.google.com/o/oauth2/auth,
hd='our_google_apps_domain.com',
access_type='offline')
返回上面粘贴的auth url!
最佳答案 身份验证成功后,您必须自己检查提供的电子邮件.我添加了您引用的文章中的代码段.我在评论后添加了额外的检查.
@app.route('/gCallback')
def callback():
# Redirect user to home page if already logged in.
if current_user is not None and current_user.is_authenticated():
return redirect(url_for('index'))
if 'error' in request.args:
if request.args.get('error') == 'access_denied':
return 'You denied access.'
return 'Error encountered.'
if 'code' not in request.args and 'state' not in request.args:
return redirect(url_for('login'))
else:
# Execution reaches here when user has
# successfully authenticated our app.
google = get_google_auth(state=session['oauth_state'])
try:
token = google.fetch_token(
Auth.TOKEN_URI,
client_secret=Auth.CLIENT_SECRET,
authorization_response=request.url)
except HTTPError:
return 'HTTPError occurred.'
google = get_google_auth(token=token)
resp = google.get(Auth.USER_INFO)
if resp.status_code == 200:
user_data = resp.json()
email = user_data['email']
"""
Your Domain specific check will come here.
"""
if email.split('@')[1] != 'domain.com':
flash('You cannot login using this email', 'error')
return redirect(url_for('login'))
user = User.query.filter_by(email=email).first()
if user is None:
user = User()
user.email = email
user.name = user_data['name']
print(token)
user.tokens = json.dumps(token)
user.avatar = user_data['picture']
db.session.add(user)
db.session.commit()
login_user(user)
return redirect(url_for('index'))
return 'Could not fetch your information.'