### Full Rails Application Example with OmniAuth and CSRF Protection Source: https://context7.com/cookpad/omniauth-rails_csrf_protection/llms.txt This example demonstrates a complete setup for OmniAuth with CSRF protection in a Rails application, including Gemfile configuration, initializer for OmniAuth, and routes. ```ruby # Gemfile gem "omniauth" gem "omniauth-github" gem "omniauth-rails_csrf_protection" # config/initializers/omniauth.rb Rails.application.config.middleware.use OmniAuth::Builder do provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'] provider :developer if Rails.env.development? end # config/routes.rb Rails.application.routes.draw do get 'auth/:provider/callback', to: 'sessions#create' get 'auth/failure', to: 'sessions#failure' get 'login', to: 'sessions#new' delete 'logout', to: 'sessions#destroy' end ``` -------------------------------- ### Add omniauth-rails_csrf_protection Gem to Gemfile (Ruby) Source: https://github.com/cookpad/omniauth-rails_csrf_protection/blob/main/README.md This code snippet shows how to add the omniauth-rails_csrf_protection gem to your Ruby on Rails application's Gemfile. After adding this line, you need to run `bundle install` to install the gem and enable its CSRF protection features. ```ruby gem "omniauth-rails_csrf_protection" ``` -------------------------------- ### Testing OmniAuth CSRF Protection Scenarios in Rails Source: https://context7.com/cookpad/omniauth-rails_csrf_protection/llms.txt These comments outline test cases for verifying OmniAuth CSRF protection. They describe expected outcomes for GET requests (404), POST requests without a token (redirect to failure), and POST requests with a valid token (proceeds to callback), demonstrating how the gem enforces CSRF token validation. ```ruby # Test that GET requests are blocked (returns 404) # GET /auth/developer => 404 Not Found # Test that POST without token fails # POST /auth/developer => Redirects to auth/failure?message=ActionController::InvalidAuthenticityToken # Test that POST with valid token succeeds # POST /auth/developer with authenticity_token => Proceeds to OAuth callback ``` -------------------------------- ### Configure OmniAuth for CSRF Protection (Ruby) Source: https://github.com/cookpad/omniauth-rails_csrf_protection/blob/main/README.md This code snippet demonstrates how to configure OmniAuth to use its built-in CSRF protection mechanism. It requires OmniAuth version 2.0.0 or later and sets a custom key for the authenticity token. This is an alternative to using the omniauth-rails_csrf_protection gem. ```ruby OmniAuth.config.request_validation_phase = OmniAuth::AuthenticityTokenProtection.new(key: :_csrf_token) ``` -------------------------------- ### Configuring OmniAuth Failure Endpoint for CSRF Errors in Rails Source: https://context7.com/cookpad/omniauth-rails_csrf_protection/llms.txt This Ruby code configures the routes for handling OmniAuth authentication failures and defines a `failure` action in the `SessionsController`. The `failure` action specifically checks for the `ActionController::InvalidAuthenticityToken` message and provides a user-friendly alert, ensuring graceful handling of CSRF-related errors. ```ruby Rails.application.routes.draw do get 'auth/failure', to: 'sessions#failure' end class SessionsController < ApplicationController def failure message = params[:message] case message when "ActionController::InvalidAuthenticityToken" redirect_to login_path, alert: "Security verification failed. Please try again." when "invalid_credentials" redirect_to login_path, alert: "Invalid credentials provided." else redirect_to login_path, alert: "Authentication failed: #{message}" end end end ``` -------------------------------- ### Convert Links to POST Forms for OAuth Source: https://context7.com/cookpad/omniauth-rails_csrf_protection/llms.txt Links initiating the OAuth request phase must be converted to HTTP POST forms that include the authenticity_token. Rails' `button_to` helper or `link_to` with `method: :post` can be used for this. ```erb <%# Using button_to (recommended) %> <%= button_to "Sign in with GitHub", "/auth/github", method: :post %> <%# Using link_to with method: :post %> <%= link_to "Sign in with Google", "/auth/google_oauth2", method: :post %> <%# Multiple providers example %>
<%= button_to "Sign in with Developer", "/auth/developer", method: :post, class: "btn" %> <%= button_to "Sign in with Facebook", "/auth/facebook", method: :post, class: "btn" %> <%= button_to "Sign in with Twitter", "/auth/twitter", method: :post, class: "btn" %>
<%# The button_to helper automatically includes the authenticity_token %> <%# Generated HTML looks like: %> <%#
%> ``` -------------------------------- ### Railtie Automatic Configuration Source: https://context7.com/cookpad/omniauth-rails_csrf_protection/llms.txt The Railtie automatically configures OmniAuth to use the TokenVerifier when the Rails application initializes. This eliminates the need for manual configuration after adding the gem. ```ruby # This happens automatically when Rails boots: # lib/omniauth/rails_csrf_protection/railtie.rb module OmniAuth module RailsCsrfProtection class Railtie < Rails::Railtie initializer "omniauth-rails_csrf_protection.initialize" do OmniAuth.config.request_validation_phase = TokenVerifier.new end end end end ``` -------------------------------- ### Rendering OmniAuth Login Buttons in Rails View Source: https://context7.com/cookpad/omniauth-rails_csrf_protection/llms.txt This ERB template renders a sign-in form with buttons for different authentication providers like GitHub and a developer option for development environments. It uses Rails' `button_to` helper to generate POST requests, which are necessary for CSRF protection. ```erb

Sign In

<%= button_to "Sign in with GitHub", "/auth/github", method: :post %> <% if Rails.env.development? %> <%= button_to "Sign in with Developer", "/auth/developer", method: :post %> <% end %> ``` -------------------------------- ### TokenVerifier Class Usage and Configuration Source: https://context7.com/cookpad/omniauth-rails_csrf_protection/llms.txt The core of the gem is the TokenVerifier class, which includes ActionController::RequestForgeryProtection. It's automatically set as OmniAuth's request_validation_phase. Manual calling is possible but typically not needed. ```ruby # The TokenVerifier is automatically configured via Railtie # It's set as OmniAuth's request validation phase: OmniAuth.config.request_validation_phase = OmniAuth::RailsCsrfProtection::TokenVerifier.new # When a request comes in, the verifier: # 1. Creates an ActionDispatch::Request from the Rack environment # 2. Calls Rails' verified_request? method # 3. Raises InvalidAuthenticityToken if verification fails # Manual usage example (typically not needed): verifier = OmniAuth::RailsCsrfProtection::TokenVerifier.new begin verifier.call(env) # env is the Rack environment hash puts "Request verified successfully" rescue ActionController::InvalidAuthenticityToken puts "Invalid or missing CSRF token" end ``` -------------------------------- ### OmniAuth Authentication Flow in Rails Controller Source: https://context7.com/cookpad/omniauth-rails_csrf_protection/llms.txt This Ruby code defines a SessionsController for handling user authentication via OmniAuth. It includes actions for rendering the login page, creating a user session, handling authentication failures, and destroying the session. It relies on Rails' session management and OmniAuth's request environment. ```ruby class SessionsController < ApplicationController def new # Render login page with OAuth buttons end def create auth = request.env['omniauth.auth'] user = User.find_or_create_from_omniauth(auth) session[:user_id] = user.id redirect_to root_path, notice: "Signed in as #{user.name}" end def failure redirect_to login_path, alert: "Authentication failed: #{params[:message]}" end def destroy session[:user_id] = nil redirect_to root_path, notice: "Signed out" end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.