Simple Application Using OAuth 2.0 and Single Sign-On (SSO)
Simple Application Using OAuth 2.0 and Single Sign-On (SSO)
- **Create `app.py`:**
Create a file named `app.py` in the project directory with the following content:
```python
from flask import Flask, redirect, url_for, session
from flask import render_template_string
from authlib.integrations.flask_client import OAuth
app = Flask(__name__)
app.secret_key = 'your_secret_key'
app.config['SESSION_COOKIE_NAME'] = 'your_session_cookie_name'
# Configure OAuth
oauth = OAuth(app)
oauth.register(
name='google',
client_id='YOUR_GOOGLE_CLIENT_ID',
client_secret='YOUR_GOOGLE_CLIENT_SECRET',
authorize_url='https://accounts.google.com/o/oauth2/auth',
authorize_params=None,
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_params=None,
refresh_token_url=None,
redirect_uri='http://localhost:5000/auth',
redirect_uri_params=None,
scope='openid profile email',
client_kwargs={'scope': 'openid profile email'},
)
@app.route('/')
def index():
if 'user' in session:
user = session['user']
return render_template_string('''
<h1>Hello {{ user['name'] }}</h1>
<a href="/logout">Logout</a>
''', user=user)
return '<a href="/login">Login with Google</a>'
@app.route('/login')
def login():
redirect_uri = url_for('auth', _external=True)
return oauth.google.authorize_redirect(redirect_uri)
@app.route('/auth')
def auth():
token = oauth.google.authorize_access_token()
user = oauth.google.parse_id_token(token)
session['user'] = user
return redirect('/')
@app.route('/logout')
def logout():
session.pop('user', None)
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
```
### **Summary**
This simple Flask application demonstrates how to integrate OAuth 2.0 and SSO using
Google as the identity provider. It covers:
- Setting up OAuth 2.0 with Google
- Handling authentication and user sessions
- Using Flask to build a basic web application
You can adapt this example to other identity providers and enhance it with
additional features like error handling, more sophisticated user interfaces, and
additional functionality based on your needs.