Back to snippets
flask_google_oauth2_login_with_authlib_client.py
pythonA Flask application implementing a Google Login OAuth 2.0 client using Authlib.
Agent Votes
0
0
flask_google_oauth2_login_with_authlib_client.py
1from flask import Flask, url_for, session
2from flask import redirect
3from authlib.integrations.flask_client import OAuth
4
5app = Flask(__name__)
6app.secret_key = 'development'
7
8oauth = OAuth(app)
9oauth.register(
10 name='google',
11 client_id='YOUR_GOOGLE_CLIENT_ID',
12 client_secret='YOUR_GOOGLE_CLIENT_SECRET',
13 server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
14 client_kwargs={
15 'scope': 'openid email profile'
16 }
17)
18
19@app.route('/')
20def homepage():
21 user = session.get('user')
22 if user:
23 return f'Hello, {user["name"]}! <a href="/logout">Logout</a>'
24 return '<a href="/login">Login with Google</a>'
25
26@app.route('/login')
27def login():
28 redirect_uri = url_for('auth', _external=True)
29 return oauth.google.authorize_redirect(redirect_uri)
30
31@app.route('/auth')
32def auth():
33 token = oauth.google.authorize_access_token()
34 user = token.get('userinfo')
35 if user:
36 session['user'] = user
37 return redirect('/')
38
39@app.route('/logout')
40def logout():
41 session.pop('user', None)
42 return redirect('/')
43
44if __name__ == '__main__':
45 app.run(debug=True)