如何将Google登录(Oauth2)限制为针对Flask WebApp的特定Google Apps域的电子邮件? [英] How do you restrict Google Login (Oauth2) to emails from a specific Google Apps domain for a Flask WebApp?

查看:182
本文介绍了如何将Google登录(Oauth2)限制为针对Flask WebApp的特定Google Apps域的电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发Flask应用程序(Python3 / Heroku)供内部公司使用,并成功地实现了基于

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&安培;范围=轮廓+电子邮件&安培;状态= STATE <强>&安培; HD = our_google_apps_domain.com &安培; ACCESS_TYPE =离线



我的理解是,这个参数应该提供客户端限制,并且只允许来自我们google应用程序域的邮件登录(服务器端,我会在这之后处理!根据 Google文档这个邮件列表文章和这些stac koverflow帖子: post1 post2 但是,尽管我的代码生成了我上面粘贴的授权URL,但我仍然可以用我的个人gmail帐户(@ gmail.com vs @our apps域名)登录。 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():
#如果已经登录,将用户重定向到主页。
如果current_user不是None和current_user.is_authenticated():
return redirect(url_for('index'))
if request.args中的'error':
如果request.args.get('error')=='access_denied':
返回'您拒绝访问'
return'遇到错误'
'如果'code'不在request.args和'state'不在request.args中:
返回重定向(url_for('login'))
else:
#当用户
#成功验证我们的应用程序时,执行到达此处。
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)
,除了HTTPError:
return'发生了HTTPError。'
google = get_google_auth(令牌=令牌)
resp = google.get Auth.USER_INFO)
如果resp.status_code == 200:
user_data = resp.json()
email = user_data ['email']



如果email.split('@')[1]!='domain.com':
flash('您无法登录('login'))
user = User.query.filter_by(email = email).first()
(如果用户是None) :
user = User()
user.email = email
user.name = user_data ['name']
print(令牌)
user.tokens = json。转储(令牌)
user.avatar = user_data ['picture']
db.session.add(用户)
db.session.commit()
login_user(用户)
return redirect(url_for('index'))
return'Could not fetch your information。'


Developing a Flask app (Python3/Heroku) for internal company use and successfully implemented Google Login (Oauth2) based on brijieshb42's article which uses requests_oauthlib.

Research has indicated that if I pass parameter "hd" (hosted domain) in my authorization url it should do the trick. E.g.

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=offline

My understanding based is that this parameter should provide client-side restriction and only allow logins from emails from our google apps domain (server-side I'll handle after this!) based on Google Documentation, this mailing list post and these stackoverflow posts: post1, post2.

However, though my code generates the authorization URL I pasted above -- I can still login with my personal gmail account (@gmail.com vs @our apps domain.com).

Can anyone shed some light as to why this isn't working? Or provide a different approach? Basically would prefer preventing non-employees from logging in.

I can share code as needed, but pretty much pasted from the brijeshb42 article and essentially looks like this:

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')

Which returns the auth url I pasted above!

解决方案

After successful authentication, you have to check the provided email yourself. I have added the code snippet from the my article that you have referenced. I have added the extra check required in after comment.

@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.'

这篇关于如何将Google登录(Oauth2)限制为针对Flask WebApp的特定Google Apps域的电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆