function azure_callback
OAuth 2.0 callback endpoint for Azure AD authentication that exchanges authorization codes for access tokens and establishes user sessions.
/tf/active/vicechatdev/docchat/app.py
734 - 777
moderate
Purpose
This Flask route handler processes the OAuth callback from Azure AD after user authentication. It receives an authorization code, exchanges it for an access token, validates the token, extracts user information, and creates an authenticated session. It handles error cases by redirecting to the login page and logs all authentication events.
Source Code
def azure_callback():
"""Azure AD OAuth callback"""
if not azure_sso:
return jsonify({'error': 'Azure SSO not configured'}), 500
# Get authorization code
code = request.args.get('code')
error = request.args.get('error')
if error:
logger.error(f"Azure auth error: {error}")
return redirect(url_for('login'))
if not code:
logger.error("No authorization code received")
return redirect(url_for('login'))
try:
# Exchange code for token
token_data = azure_sso.get_token_from_code(code)
if not token_data:
logger.error("Failed to get token from Azure")
return redirect(url_for('login'))
# Validate token and extract user info
user_info = validate_azure_token(token_data)
if not user_info:
logger.error("Failed to validate Azure token")
return redirect(url_for('login'))
# Store user info in session
session['user'] = user_info
session['token'] = token_data.get('access_token')
session.permanent = True
logger.info(f"User {user_info.get('email')} logged in successfully")
return redirect(url_for('index'))
except Exception as e:
logger.error(f"Error in Azure callback: {e}", exc_info=True)
return redirect(url_for('login'))
Return Value
Returns a Flask Response object. On success, redirects to the 'index' route. On failure (missing configuration, errors, or validation failures), redirects to the 'login' route. May return a JSON error response with status 500 if Azure SSO is not configured.
Dependencies
flaskloggingwerkzeug
Required Imports
from flask import Flask
from flask import request
from flask import jsonify
from flask import session
from flask import redirect
from flask import url_for
import logging
from auth.azure_auth import setup_azure_sso
from auth.azure_auth import validate_azure_token
Usage Example
# This is a Flask route callback, not called directly
# Setup:
from flask import Flask
from auth.azure_auth import setup_azure_sso, validate_azure_token
import logging
app = Flask(__name__)
app.secret_key = 'your-secret-key'
logger = logging.getLogger(__name__)
# Initialize Azure SSO
azure_sso = setup_azure_sso(
client_id='your-client-id',
client_secret='your-client-secret',
tenant_id='your-tenant-id',
redirect_uri='https://yourapp.com/auth/azure/callback'
)
@app.route('/auth/azure/callback')
def azure_callback():
# Function implementation here
pass
# User flow:
# 1. User clicks login and is redirected to Azure AD
# 2. User authenticates with Azure AD
# 3. Azure AD redirects to /auth/azure/callback?code=AUTH_CODE
# 4. This function processes the callback
# 5. User is redirected to index page with active session
Best Practices
- Ensure azure_sso is properly initialized before the application starts accepting requests
- Configure Flask session with secure settings (secure cookies, httponly, samesite) in production
- Use HTTPS in production to protect tokens and session data
- Implement proper error handling and logging for security auditing
- Set session.permanent = True to control session lifetime with PERMANENT_SESSION_LIFETIME
- Store minimal user information in session; consider using server-side session storage for sensitive data
- Validate the state parameter (CSRF protection) if implementing full OAuth 2.0 security
- Consider implementing token refresh logic for long-lived sessions
- Ensure the redirect URI registered in Azure AD exactly matches the callback URL
- Log authentication events for security monitoring and compliance
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function auth_callback_v2 95.5% similar
-
function auth_callback_v1 94.9% similar
-
function auth_callback 94.4% similar
-
class SSOCallbackHandler 76.3% similar
-
function process_auth_code 74.8% similar