In a Rails OmniAuth callback, what does request.env['omniauth.auth'] contain, and how should the action find the local user from it?
answer
- provider, uid, info, credentials, extra
- uid is stable, email is not
- an identities table per provider
- unique index on provider and uid
- never put the hash in the session
basics
~20 sIt holds an OmniAuth::AuthHash with provider, uid, info (name, email and similar), credentials and extra. The action should look up a local identity by provider plus uid, behind a unique index, and treat email only as profile data.
solid answer
~40 s`request.env["omniauth.auth"]` is an `OmniAuth::AuthHash`, readable as `auth.provider`, `auth.uid`, `auth.info.email` or with string keys. `provider` is the strategy name, `uid` the provider's identifier for that account, `info` a normalised profile (name, email, nickname, image and so on, whatever the provider shares), `credentials` any tokens the strategy returns, and `extra` the raw provider response. Find the member by `provider` and `uid`, usually through an `identities` table with `belongs_to :member` and a unique index on `[provider, uid]`, because that pair is the only value the provider promises to keep stable and unique. Email can change, may be missing, and means nothing across providers, so matching or merging accounts on it is a policy decision, not a lookup key. Read what you need and discard the rest; storing the whole hash in a cookie session can overflow it.
code
ruby · 14 linesclass Member < ApplicationRecord
has_many :identities, dependent: :destroy
def self.from_omniauth(auth)
identity = Identity.find_by(provider: auth.provider, uid: auth.uid.to_s)
return identity.member if identity
transaction do
member = create!(display_name: auth.info.name, email: auth.info.email)
member.identities.create!(provider: auth.provider, uid: auth.uid.to_s)
member
end
end
endgo deeper
Recall the five top-level keys of the auth hash and that provider plus uid, not email, identifies the account.
Design the identities table with its unique index, write the find-or-create path, and explain why email changes or goes missing.
Handle concurrent callbacks with the unique index, the connect-while-signed-in case, cookie-size limits and token storage as distinct concerns.
Set the rules for which provider data the product stores and for how long, and who decides when two identities may share one account.
## What the hash is When the callback phase succeeds, the strategy builds an **`OmniAuth::AuthHash`** and sets it on the Rack env as `omniauth.auth`. In a Rails controller you read it with `request.env["omniauth.auth"]`. `AuthHash` is a Hashie-based key store, so `auth.uid`, `auth["uid"]` and `auth.info.email` all work. Every strategy fills the same top-level schema: | Key | Contents | Use it for | |---|---|---| | `provider` | the strategy name, e.g. `"github"` | half of the lookup key | | `uid` | the provider's identifier for this account | the other half of the lookup key | | `info` | an `InfoHash`: `name`, `email`, `nickname`, `first_name`, `last_name`, `image` and similar, as available | profile defaults | | `credentials` | tokens the strategy obtained, if any | calling the provider's API later | | `extra` | further provider data the strategy chooses to pass on | anything not normalised | `InfoHash#name` falls back to first plus last name, then `nickname`, then `email`, and `AuthHash#valid?` is true only when `provider`, `uid` and a name are present. Which `info` fields arrive depends on the provider, the scopes you request and the user's own privacy settings. ## The lookup key is provider plus uid A provider guarantees that `uid` identifies one account **within that provider**. Nothing else in the hash carries that promise: - **Email changes.** A member can change the address on their code-hosting account; a lookup by email then creates a second local account or, worse, finds someone else's. - **Email can be absent.** Some providers hide it unless a scope is granted or the user allows it, so `auth.info.email` can be `nil`. - **Email means nothing across providers.** The same address at two providers does not prove the same person controls both. When to trust a provider's verified address for linking is an account-linking policy question, owned outside this answer. So the model is a separate **identity** row per provider account: ```ruby # migration create_table :identities do |t| t.references :member, null: false, foreign_key: true t.string :provider, null: false t.string :uid, null: false t.timestamps end add_index :identities, [:provider, :uid], unique: true ``` A member can then hold several identities, and adding a second provider is a new row rather than a new column. ## Writing the lookup 1. Read `auth.provider` and `auth.uid.to_s`. Store `uid` as a string column; providers differ in whether it is numeric. 2. Find the identity: `Identity.find_by(provider:, uid:)`. 3. If found, sign in `identity.member`. 4. If not, either create a member plus identity (sign-up through the provider) or, when a member is already signed in, attach the identity to them (connect an account). 5. Use `create_or_find_by!` or rescue `ActiveRecord::RecordNotUnique` so two simultaneous callbacks cannot create duplicate rows; the unique index is what makes that safe. ## What not to keep - **Not the whole hash in the session.** With the default cookie store the session must fit in 4096 bytes; the `extra` section alone can exceed that and raise `ActionDispatch::Cookies::CookieOverflow`. Store the member's id through your normal sign-in code. - **Not tokens in plain columns.** If you keep `credentials` to call the provider's API, treat them as secrets. - **Not trust in `info` for authorisation.** A display name or nickname is user-editable profile data. The env also carries `omniauth.origin` (where the user started) and `omniauth.params` (the query string sent to `/auth/:provider`), both copied from the session by the callback phase.
- A member already signed in clicks Connect GitHub; how does the callback differ?The callback sees a current member, so instead of finding or creating a member it attaches the identity: `current_member.identities.create!(provider: auth.provider, uid: auth.uid.to_s)`. If that pair already belongs to another member, the unique index refuses it and you show an error rather than moving the identity silently.
- Why is auth.info.email sometimes nil for a provider that has the user's address?The strategy fills `info` only with what the provider returns for the granted scopes, and some providers omit an address the user has marked private. Request the scope the strategy documents for email, and design the sign-up so a missing email is handled rather than raising on a `null: false` column.
- Find the user with User.find_by(email: auth.info.email) and sign them in.
- Store request.env["omniauth.auth"] in the session for later requests.
- The uid is unique across all providers, so provider need not be stored.
- auth.info.name proves who the user is, so it can key the account.
- OmniAuth creates the User record when the callback succeeds.