How do you restrict Google Login (Oauth2) to emails from a specific Google Apps domain for a Flask WebApp? How do you restrict Google Login (Oauth2) to emails from a specific Google Apps domain for a Flask WebApp? flask flask

How do you restrict Google Login (Oauth2) to emails from a specific Google Apps domain for a Flask WebApp?


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


When you create the authorization URL, you can append optional parameters; appending hd= ... will do the trick:

auth_url, state = google.authorization_url(AUTH_URI, access_type='offline', hd='savv.ch')

This has many benefits. For example Google will then automatically pick the right account (if it matches the domain), which potentially saves a step in the Auth process, if the user is logged into multiple accounts.

http://requests-oauthlib.readthedocs.io/en/latest/api.html#requests_oauthlib.OAuth2Session.authorization_url