function auth_callback_v1
OAuth2 callback handler for Azure SSO authentication that processes authorization codes, exchanges them for access tokens, and establishes user sessions.
/tf/active/vicechatdev/vice_ai/new_app.py
437 - 476
moderate
Purpose
This Flask route handler processes the OAuth2 callback from Azure Active Directory after user authentication. It extracts the authorization code, exchanges it for an access token, stores user information in the session, and redirects to the appropriate page. It handles dynamic redirect URIs for proxy/load balancer scenarios and includes comprehensive error handling.
Source Code
def auth_callback():
"""Authentication callback"""
if AZURE_SSO_AVAILABLE:
try:
auth_code = request.args.get('code')
if not auth_code:
flash('Authorization failed', 'error')
return redirect(url_for('login'))
# Build dynamic redirect URI based on current request
scheme = request.headers.get('X-Forwarded-Proto', request.scheme)
host = request.headers.get('X-Forwarded-Host', request.host)
dynamic_redirect_uri = f"{scheme}://{host}/auth/callback"
# Temporarily update the redirect_uri for token exchange
original_redirect = azure_sso.redirect_uri
azure_sso.redirect_uri = dynamic_redirect_uri
token_response = azure_sso.get_token_from_code(auth_code)
azure_sso.redirect_uri = original_redirect # Restore original
if 'access_token' in token_response:
session.permanent = True # Make session persistent
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('index'))
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'))
else:
return redirect(url_for('index'))
Return Value
Returns a Flask redirect response object. On success, redirects to 'index' route with user session established. On failure or when Azure SSO is unavailable, redirects to 'login' route with appropriate flash messages. Possible redirect targets: url_for('index') on success, url_for('login') on error or missing auth code.
Dependencies
flaskloggingdatetime
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
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from auth.azure_auth import AzureSSO
Condition: Required for Azure SSO authentication functionality. Must be initialized as 'azure_sso' instance before this function is called
Required (conditional)Usage Example
# This is a Flask route callback, not called directly
# Setup required:
from flask import Flask, session
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_AVAILABLE = True
azure_sso = AzureSSO(
client_id='your-client-id',
client_secret='your-client-secret',
tenant_id='your-tenant-id',
redirect_uri='https://yourapp.com/auth/callback'
)
@app.route('/auth/callback')
def auth_callback():
# Function implementation here
pass
# User flow:
# 1. User initiates login, gets redirected to Azure AD
# 2. Azure AD redirects back to /auth/callback?code=AUTH_CODE
# 3. This function processes the callback automatically
# 4. User session is established and redirected to index
# Access user info after successful auth:
# user_name = session.get('user', {}).get('name')
# user_email = session.get('user', {}).get('email')
Best Practices
- Ensure AZURE_SSO_AVAILABLE flag is properly set based on environment configuration
- The function handles dynamic redirect URIs for proxy/load balancer scenarios using X-Forwarded-Proto and X-Forwarded-Host headers
- Session is set to permanent to persist across browser sessions - adjust session.permanent based on security requirements
- Always validate the authorization code exists before processing
- The function temporarily modifies azure_sso.redirect_uri for token exchange then restores it - this is necessary for dynamic proxy scenarios
- Error handling logs exceptions but shows generic error messages to users for security
- Flash messages are used for user feedback - ensure Flask flash message rendering is configured in templates
- User information is stored in session including login_time for audit purposes
- If Azure SSO is not available, the function gracefully redirects to index without authentication
- Consider implementing CSRF protection for the OAuth2 state parameter
- Ensure proper session timeout configuration in Flask app settings
- The access_token is stored in session - consider token refresh logic for long-lived sessions
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function auth_callback 95.8% similar
-
function azure_callback 94.9% similar
-
function auth_callback_v2 94.6% similar
-
function process_auth_code 76.9% similar
-
class SSOCallbackHandler 76.1% similar