python-3.x - 您如何将 Google Login (Oauth2) 限制为来自 Flask WebApp 的特定 Google Apps 域的电子邮件?

标签 python-3.x heroku flask google-oauth

开发 Flask 应用程序(Python3/Heroku)供公司内部使用,并基于 brijieshb42's article 成功实现了 Google 登录(Oauth2)它使用 requests_oauthlib。

研究表明,如果我在我的授权 url 中传递参数“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.'

关于python-3.x - 您如何将 Google Login (Oauth2) 限制为来自 Flask WebApp 的特定 Google Apps 域的电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34235590/

相关文章:

python - 单元测试 Flask-Principal 应用程序

python - 为什么 `for` 循环计算真值的速度如此之快?

python - PriorityQueue 按对象属性排序

ruby-on-rails - Heroku bundler 不删除旧的 gems 版本

python - Flask在每个模块的每个模板中显示用户注册或已经登录

python - Flask:如何在 session 中存储凭据并检索它们?

python - 期望非 bool 返回值时返回 False 是一种好习惯吗?

python - 在 Python 3 中执行 Windll.version.GetFileVersionInfoSizeA() 失败

html - 如何使用 rails 5 在 Heroku 上的我的应用程序上显示图像和文本

python - 在推送到 S3 之前,是否有更干净的方法来旋转通过 Flask 上传的智能手机图像?