🔍 Code Extractor

function azure_callback

Maturity: 50

OAuth 2.0 callback endpoint for Azure AD authentication that exchanges authorization codes for access tokens and establishes user sessions.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
734 - 777
Complexity:
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

  • flask
  • logging
  • werkzeug

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function auth_callback_v2 95.5% similar

    Flask route handler that processes OAuth 2.0 callback from Azure AD, exchanges authorization code for access tokens, and establishes user session.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function auth_callback_v1 94.9% similar

    OAuth2 callback handler for Azure SSO authentication that processes authorization codes, exchanges them for access tokens, and establishes user sessions.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function auth_callback 94.4% similar

    OAuth callback handler that processes Azure SSO authentication responses, exchanges authorization codes for access tokens, and establishes user sessions.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • class SSOCallbackHandler 76.3% similar

    A Tornado RequestHandler that processes OAuth 2.0 callbacks from Azure AD, exchanges authorization codes for access tokens, validates user identity, and sets authentication cookies for SSO integration.

    From: /tf/active/vicechatdev/CDocs/sso_plugin.py
  • function process_auth_code 74.8% similar

    Processes OAuth authorization codes from POST requests, exchanges them for access tokens via Azure SSO, and authenticates users into the application.

    From: /tf/active/vicechatdev/CDocs/main.py
← Back to Browse