🔍 Code Extractor

function auth_callback

Maturity: 54

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
650 - 676
Complexity:
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

  • flask
  • datetime
  • logging

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function auth_callback_v1 95.8% 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_v2 94.8% 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 azure_callback 94.4% 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
  • class SSOCallbackHandler 79.7% 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 76.7% 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