Skip to content

Add after_request_phase callback hook - #1147

Merged
BobbyMcWho merged 3 commits into
omniauth:masterfrom
gerardo-navarro:gerardo-navarro-feat-after-request-phase-hook
Oct 1, 2025
Merged

BobbyMcWho merged 3 commits into
omniauth:masterfrom
gerardo-navarro:gerardo-navarro-feat-after-request-phase-hook

Conversation

@gerardo-navarro

@gerardo-navarro gerardo-navarro commented Jul 16, 2025 •

Copy link
Copy Markdown
Contributor

Motivation

OmniAuth currently provides several lifecycle hooks (before_request_phase, before_callback_phase, before_options_phase) that allow developers to execute custom logic before the different phases of an authentication flow. However, there is currently no hook for executing custom logic after the request phase completes.

This limitation becomes problematic when you need to, for example:

  • Access attributes calculated during the request phase, see example use case below
  • Clean up resources allocated during the request phase (database connections, temporary files, etc.)
  • Log completion metrics for monitoring and analytics (request duration, success/failure rates)
  • Implement custom caching or invalidation logic after authentication requests
  • Send notifications or trigger webhooks after authentication attempts
  • Perform audit logging for security compliance requirements
  • Execute cleanup code that must run regardless of whether the request phase succeeded or failed

Without an after_request_phase hook, developers are forced to:

  1. Monkey-patch OmniAuth internals (brittle and unmaintainable)
  2. Wrap their entire authentication flow in custom middleware (complex and error-prone)
  3. Switch to a self-coded or alternative multi-provider authentication.

Solution

This PR introduces an after_request_phase callback that mirrors the existing before_request_phase pattern, providing a clean and consistent API for post-request-phase logic.

Changes

  • ✅ Added after_request_phase configuration option to OmniAuth::Configuration
  • ✅ Added after_request_phase method to OmniAuth::Builder for easy configuration
  • ✅ Implemented callback execution in both normal and test modes (request_call and mock_request_call)
  • ✅ Ensured callback executes after all request phase logic while preserving return values
  • ✅ Added comprehensive test coverage matching existing callback patterns
  • ✅ Maintained backward compatibility (no breaking changes)

Usage Example

# Configure globally
OmniAuth.configure do |config|
  config.after_request_phase do |env|
    # Log authentication attempt
    Rails.logger.info "Authentication request completed for #{env['PATH_INFO']}"
    
    # Clean up any resources
    cleanup_temp_resources(env)
    
    # Send metrics
    track_auth_request_completion(env)
  end
end

# Or configure per-strategy
use OmniAuth::Builder do
  after_request_phase do |env|
    # Strategy-specific cleanup
  end
  
  provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
end

Testing

All existing tests pass, and new tests have been added to cover:

  • Configuration of after_request_phase via OmniAuth.configure
  • Configuration of after_request_phase via OmniAuth::Builder
  • Execution of the callback during request phase in both normal and test modes
  • Proper cleanup and isolation between tests

Why This Matters

This feature completes OmniAuth's lifecycle hook ecosystem, providing developers with the full set of tools needed to implement robust, production-ready authentication flows. It follows established patterns in the codebase and maintains the same level of reliability and test coverage as existing hooks.

The implementation is non-intrusive and maintains full backward compatibility while opening up new possibilities for monitoring, cleanup, and custom logic execution.

Example Use Case: GitLab Step-Up Authentication

GitLab's step-up authentication requires capturing the OAuth state parameter after it's generated to validate returning users. The OpenID Connect strategy generates this UUID during the request phase in authorize_uri by calling new_state, but no existing hook allows access to this value after generation.

The Problem:

  • before_request_phase: Runs before state generation
  • before_callback_phase: Runs after user returns with a callback from IdP
  • Gap: No hook to capture state after generation but before redirect

The Solution:

config.after_request_phase do |env|
  state = env['rack.session']['omniauth.state']
  store_step_up_auth_state(env, state) if step_up_auth_flow?(env)
end

This enables GitLab to securely capture and store the generated state parameter for step-up authentication validation without monkey-patching OmniAuth internals.

There are cases when you want to execute some code
after the request phase but before the callback phase.
For example, you might want to perform some logging,
access the result from the request phase, or modify the environment.

This commit adds an `after_request_phase` hook to the OmniAuth
builder, allowing developers to define custom behavior
after the request phase is completed. This hook is executed
after the request phase but before the callback phase,
providing a convenient place to handle any necessary logic.
@gerardo-navarro

gerardo-navarro commented Jul 30, 2025 •

Copy link
Copy Markdown
Contributor Author

@BobbyMcWho Do you have the capacity to review this PR? Let me know if I can do anything to clarify or help. 🙏

/cc @bufferoverflow @fh1ch

@gerardo-navarro

Copy link
Copy Markdown
Contributor Author

@BobbyMcWho Here is a gentle nudge regarding this PR. Do you have the bandwidth to take a look at this?

@BobbyMcWho BobbyMcWho left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I keep seeing this and forgetting to follow up.

Comment thread lib/omniauth/strategy.rb Resolved
Comment thread lib/omniauth/strategy.rb Resolved
@BobbyMcWho
BobbyMcWho self-requested a review October 1, 2025 16:58
@BobbyMcWho
BobbyMcWho merged commit 3a249af into omniauth:master Oct 1, 2025
@BobbyMcWho

Copy link
Copy Markdown
Member

@gerardo-navarro

gerardo-navarro commented Oct 2, 2025 •

Copy link
Copy Markdown
Contributor Author

@BobbyMcWho Thanks for reviewing, approving and also releasing a version. 🙇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants