🔍 Code Extractor

function auth_callback_v2

Maturity: 52

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

File:
/tf/active/vicechatdev/vice_ai/app.py
Lines:
660 - 689
Complexity:
moderate

Purpose

This function serves as the OAuth 2.0 callback endpoint for Azure AD authentication. It receives the authorization code from Azure AD after user consent, exchanges it for access tokens using the azure_sso service, extracts user information from ID token claims, stores authentication data in the Flask session, and redirects users to the appropriate page based on authentication success or failure. It implements error handling with user-friendly flash messages and logging.

Source Code

def auth_callback():
    """Handle OAuth callback from Azure AD"""
    try:
        # Get authorization code from callback
        auth_code = request.args.get('code')
        if not auth_code:
            flash('Authorization failed - no code received', 'error')
            return redirect(url_for('login'))
        
        # Exchange code for tokens
        token_response = azure_sso.get_token_from_code(auth_code)
        
        if 'access_token' in token_response:
            # Store user info in session
            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('chat'))
        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 the 'chat' route. On any failure (missing code, token exchange failure, or exception), redirects to the 'login' route. Also sets flash messages to communicate status to the user ('success' or 'error' category).

Dependencies

  • flask
  • logging
  • datetime

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

Usage Example

# This function is automatically called by Flask when Azure AD redirects to /auth/callback
# It should not be called directly. Instead, configure it as a route:

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-here'
logger = logging.getLogger(__name__)

# Initialize Azure SSO
azure_sso = AzureSSO(
    client_id='your-client-id',
    client_secret='your-client-secret',
    tenant_id='your-tenant-id',
    redirect_uri='http://localhost:5000/auth/callback'
)

@app.route('/auth/callback')
def auth_callback():
    """Handle OAuth callback from Azure AD"""
    try:
        auth_code = request.args.get('code')
        if not auth_code:
            flash('Authorization failed - no code received', '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('chat'))
        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 initiates login by visiting the Azure AD authorization URL
# Azure AD redirects back to /auth/callback with authorization code
# This function processes the callback automatically

Best Practices

  • Ensure Flask secret_key is set to a strong, random value for secure session management
  • Always validate the presence of the authorization code before attempting token exchange
  • Store only necessary user information in the session to minimize security risks
  • Use HTTPS in production to protect tokens and session data in transit
  • Implement CSRF protection for the OAuth flow using state parameter validation
  • Set appropriate session timeout values to balance security and user experience
  • Log authentication errors for security monitoring but avoid logging sensitive token data
  • Consider implementing token refresh logic to handle expired access tokens
  • Validate the redirect_uri matches what was registered in Azure AD
  • Handle edge cases like user denying consent or network failures during token exchange
  • Use flash messages appropriately to inform users of authentication status without exposing technical details

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function azure_callback 95.5% similar

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

    From: /tf/active/vicechatdev/docchat/app.py
  • function auth_callback 94.8% 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
  • function auth_callback_v1 94.6% 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
  • class SSOCallbackHandler 76.6% 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 login_v1 75.2% similar

    Flask route handler that manages user authentication by redirecting authenticated users to the index page, initiating Azure SSO login for production, or creating a development session for local testing.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse