function auth_callback
OAuth callback handler that processes Azure SSO authentication responses, exchanges authorization codes for access tokens, and establishes user sessions.
/tf/active/vicechatdev/vice_ai/complex_app.py
650 - 676
moderate
Purpose
This Flask route handler manages the OAuth 2.0 callback flow for Azure Single Sign-On (SSO). It receives an authorization code from Azure AD, exchanges it for an access token, extracts user information from ID token claims, stores authentication data in the session, and redirects users to the appropriate page based on authentication success or failure. It includes comprehensive error handling and user feedback via flash messages.
Source Code
def auth_callback():
"""Handle OAuth callback"""
try:
auth_code = request.args.get('code')
if not auth_code:
flash('Authorization failed', 'error')
return redirect(url_for('login'))
token_response = azure_sso.get_token_from_code(auth_code)
if 'access_token' in token_response:
session['access_token'] = token_response['access_token']
session['user'] = {
'name': token_response.get('id_token_claims', {}).get('name', 'User'),
'email': token_response.get('id_token_claims', {}).get('email', ''),
'login_time': datetime.now().isoformat()
}
flash('Login successful!', 'success')
return redirect(url_for('document_workspace'))
else:
flash('Authentication failed', 'error')
return redirect(url_for('login'))
except Exception as e:
logger.error(f"Authentication error: {e}")
flash('Authentication error occurred', 'error')
return redirect(url_for('login'))
Return Value
Returns a Flask redirect response object. On successful authentication, redirects to 'document_workspace' route. On failure (missing code, authentication error, or exception), redirects to 'login' route. All redirects are accompanied by flash messages indicating success or failure status.
Dependencies
flaskdatetimelogging
Required Imports
from flask import request
from flask import session
from flask import redirect
from flask import url_for
from flask import flash
from datetime import datetime
Usage Example
# This function is used as a Flask route callback
# Setup required:
from flask import Flask, session, request, redirect, url_for, flash
from datetime import datetime
from auth.azure_auth import AzureSSO
import logging
app = Flask(__name__)
app.secret_key = 'your-secret-key'
logger = logging.getLogger(__name__)
# Initialize Azure SSO
azure_sso = AzureSSO(
tenant_id='your-tenant-id',
client_id='your-client-id',
client_secret='your-client-secret',
redirect_uri='http://localhost:5000/auth/callback'
)
@app.route('/auth/callback')
def auth_callback():
"""Handle OAuth callback"""
try:
auth_code = request.args.get('code')
if not auth_code:
flash('Authorization failed', 'error')
return redirect(url_for('login'))
token_response = azure_sso.get_token_from_code(auth_code)
if 'access_token' in token_response:
session['access_token'] = token_response['access_token']
session['user'] = {
'name': token_response.get('id_token_claims', {}).get('name', 'User'),
'email': token_response.get('id_token_claims', {}).get('email', ''),
'login_time': datetime.now().isoformat()
}
flash('Login successful!', 'success')
return redirect(url_for('document_workspace'))
else:
flash('Authentication failed', 'error')
return redirect(url_for('login'))
except Exception as e:
logger.error(f"Authentication error: {e}")
flash('Authentication error occurred', 'error')
return redirect(url_for('login'))
# User is redirected here from Azure AD after authentication
# Example callback URL: http://localhost:5000/auth/callback?code=AUTH_CODE_HERE
Best Practices
- Ensure Flask session secret key is set to a strong, random value in production
- Configure HTTPS for the callback URL in production environments to protect tokens in transit
- Implement CSRF protection for the OAuth flow using state parameters
- Set appropriate session timeout values to balance security and user experience
- Store only necessary user information in the session; avoid storing sensitive data
- Implement proper error logging without exposing sensitive information to end users
- Validate the token response structure before accessing nested claims
- Consider implementing token refresh logic for long-lived sessions
- Use secure session cookies with httponly and secure flags enabled
- Implement rate limiting on the callback endpoint to prevent abuse
- Ensure the azure_sso object properly validates tokens and handles token expiration
- Consider adding state parameter validation to prevent CSRF attacks in OAuth flow
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function auth_callback_v1 95.8% similar
-
function auth_callback_v2 94.8% similar
-
function azure_callback 94.4% similar
-
class SSOCallbackHandler 79.7% similar
-
function process_auth_code 76.7% similar