How Do You Restrict Google Login (oauth2) To Emails From A Specific Google Apps Domain For A Flask Webapp?
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. Res
Solution 1:
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')defcallback():
# Redirect user to home page if already logged in.if current_user isnotNoneand 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'notin request.args and'state'notin 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 isNone:
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.'
Solution 2:
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.
Post a Comment for "How Do You Restrict Google Login (oauth2) To Emails From A Specific Google Apps Domain For A Flask Webapp?"