skip to content

In a Rails app using OmniAuth 2, how does a Sign in with GitHub click travel from the button to your callback action?

level: juniorimportance: must knowfreq 50%

answer

  1. Rack middleware, not a controller
  2. request phase on POST /auth/:provider
  3. callback phase at /auth/:provider/callback
  4. request.env["omniauth.auth"]
  5. you write the callback route

basics

~20 s

OmniAuth::Builder is Rack middleware. A POST to /auth/github runs the request phase and redirects to the provider; the provider sends the browser back to /auth/github/callback, where the middleware stores the result in request.env["omniauth.auth"] and passes the request to your routed action.

solid answer

~40 s

In `config/initializers/omniauth.rb`, `Rails.application.config.middleware.use OmniAuth::Builder do provider :github, id, secret end` adds one strategy middleware per `provider`; the `:github` strategy itself comes from a separate strategy gem. The page renders `button_to "Sign in with GitHub", "/auth/github", data: { turbo: false }`, because OmniAuth 2 starts the **request phase** only on POST. The middleware intercepts that POST, checks its CSRF token, and redirects the browser to the provider. When the provider sends the browser back to `/auth/github/callback`, the **callback phase** completes the exchange, builds the auth hash, puts it in `request.env["omniauth.auth"]`, and only then lets the request continue into Rails. There you route it, `get "auth/:provider/callback", to: "omniauth_sessions#create"`, and the action finds the local user and signs them in. Failures are redirected to `/auth/failure`.

code

ruby · 17 lines
ruby
# config/routes.rb
get "auth/:provider/callback", to: "omniauth_sessions#create"
get "auth/failure", to: "omniauth_sessions#failure"

# app/controllers/omniauth_sessions_controller.rb
class OmniauthSessionsController < ApplicationController
  def create
    auth = request.env["omniauth.auth"]
    member = Member.from_omniauth(auth)
    start_member_session(member) # your own sign-in code
    redirect_to url_from(request.env["omniauth.origin"]) || root_path
  end

  def failure
    redirect_to root_path, alert: "Sign-in with #{params[:strategy]} failed: #{params[:message]}"
  end
end

go deeper

for a junior

Recall the two paths, /auth/:provider and /auth/:provider/callback, that the first must be a POST, and that the callback action reads request.env["omniauth.auth"].

for a middle

Explain that strategies are Rack middleware, what each phase stores in the session and env, and why the app must route the callback and /auth/failure itself.

for a senior

Account for Turbo and cross-origin redirects, providers that POST the callback, the origin value as an open-redirect risk, and the development-only raise in the failure endpoint.

for a principal

Decide where third-party sign-in fits beside password sign-in and which provider data the product may keep, before the first strategy is added.

## Where OmniAuth sits OmniAuth is not a Rails engine and has no controllers. It is **Rack middleware**: code that sees every request before Rails' router does. `OmniAuth::Builder` is a subclass of `Rack::Builder`, and each `provider` line inside it calls `use` with a **strategy** class, so a block with three providers adds three middlewares. Strategies for real providers ship as separate gems; if one is missing, `provider` raises a `LoadError` suggesting a gem such as `omniauth-github`. Take a **developer-community site** that lets members sign in with their code-hosting account: ```ruby # config/initializers/omniauth.rb Rails.application.config.middleware.use OmniAuth::Builder do provider :developer unless Rails.env.production? provider :github, Rails.application.credentials.dig(:github, :client_id), Rails.application.credentials.dig(:github, :client_secret), scope: "user:email" end ``` Each strategy watches two paths under the `path_prefix`, which defaults to `/auth`. It also needs a Rack session: without one it raises `OmniAuth::NoSessionError`. ## Phase 1: the request phase 1. The sign-in page posts a form to `/auth/github`. OmniAuth 2's `allowed_request_methods` defaults to `[:post]`, so a plain link (a GET) is not intercepted at all. 2. The strategy stores the query string in `session["omniauth.params"]` and, by default, an `origin` parameter or the referer in `session["omniauth.origin"]`. 3. It runs `request_validation_phase`, the CSRF check (in a Rails app, usually supplied by `omniauth-rails_csrf_protection`). 4. It calls the strategy's `request_phase`, which for an OAuth provider redirects the browser to the provider's consent page. Turbo submits forms with `fetch`, which cannot follow a redirect to another origin as a page visit, so the button opts out with `data: { turbo: false }`. ## Phase 2: the callback phase The provider redirects the browser to `/auth/github/callback`. The middleware recognises the path and: - moves `omniauth.origin` and `omniauth.params` from the session into `request.env`; - runs the strategy's `callback_phase`, which talks to the provider and builds an `OmniAuth::AuthHash`; - sets `request.env["omniauth.auth"]` to that hash; - calls the rest of the app, so the request **continues into Rails**. OmniAuth does not create users or sessions. If no route matches the callback path, the request ends in a routing error, so the app must route it. ## The Rails side | Piece | Code | |---|---| | Gems | `omniauth`, a strategy gem, `omniauth-rails_csrf_protection` | | Middleware | `config.middleware.use OmniAuth::Builder` in an initializer | | Button | `button_to "Sign in with GitHub", "/auth/github", data: { turbo: false }` | | Callback route | `get "auth/:provider/callback", to: "omniauth_sessions#create"` | | Failure route | `get "auth/failure", to: "omniauth_sessions#failure"` | | Action | read `request.env["omniauth.auth"]`, find the user by provider and uid, sign in | Some providers return to the callback with a POST; for those, add a `post` route for the same path. ## Mistakes that break the flow - **A link instead of a form.** Under OmniAuth 2 a GET to `/auth/github` is not intercepted and ends in a 404. - **No CSRF bridge.** Without `omniauth-rails_csrf_protection` (or an equivalent `request_validation_phase`), OmniAuth's default check cannot read Rails' token and every sign-in fails. - **No callback route.** The middleware hands the request on; without a route Rails answers with a routing error. - **An API-only app with no session middleware.** The strategy raises `OmniAuth::NoSessionError` because it needs a Rack session to carry state between the two phases. - **Trusting `omniauth.origin` blindly.** It comes from a request parameter or the referer, so redirecting to it unchecked is an open redirect. ## When something goes wrong Any error in either phase calls the strategy's `fail!`, which records `omniauth.error`, `omniauth.error.type` and `omniauth.error.strategy` in the env and calls `OmniAuth.config.on_failure`. The default, `OmniAuth::FailureEndpoint`, redirects to `/auth/failure?message=<type>&strategy=<name>`, or raises the error instead when `ENV["RACK_ENV"]` is in `failure_raise_out_environments` (default `["development"]`). Every problem a strategy reports ends here, so `/auth/failure` needs a page that reads `params[:message]` and `params[:strategy]` and offers another try.

  • What is the Developer strategy for, and why must it stay out of production?
    `provider :developer` ships with OmniAuth and renders a plain form asking for a name and email, then returns them as the auth hash with the email as `uid`. It lets you build the callback before registering an app with a real provider. It has no security at all, since anyone can type any email, so it is guarded with `unless Rails.env.production?`.
  • How does the callback action learn where the user was before signing in?
    During the request phase OmniAuth stores an `origin` parameter, or the referer, in `session["omniauth.origin"]`, and the callback phase moves it to `request.env["omniauth.origin"]`. Pass it through Rails' `url_from`, which returns `nil` for a URL on another host, before redirecting to it, or you have built an open redirect.

  • OmniAuth adds its own SessionsController that signs the user in.
  • A link_to "/auth/github" starts the OmniAuth 2 flow.
  • The callback route is added by OmniAuth::Builder, so routes.rb needs nothing.
  • omniauth.auth is available in params[:omniauth] in the callback action.
  • provider :github works with only the omniauth gem installed.

Assumes OmniAuth 2.1 on Rails 8.1; since OmniAuth 2.0 the request phase answers POST only, so the sign-in control is a form button, not a link.