With the Doorkeeper gem, what do doorkeeper:install, use_doorkeeper and resource_owner_authenticator each contribute when a Rails app becomes an OAuth 2 provider?
answer
- initializer, locale file, one route line
- a second generator writes the tables
- everything drawn under /oauth
- block instance_eval'd in Doorkeeper's controllers
- admin_authenticator guards /oauth/applications
basics
~10 sDoorkeeper's doorkeeper:install generator writes the initializer and adds use_doorkeeper, which draws /oauth/authorize, /oauth/token and the client screens; resource_owner_authenticator is the block that returns the signed-in user or redirects to sign-in.
solid answer
~30 s`bin/rails generate doorkeeper:install` writes `config/initializers/doorkeeper.rb`, copies `config/locales/doorkeeper.en.yml` and adds `use_doorkeeper` to `config/routes.rb`; the tables come from a second generator, `doorkeeper:migration`, which creates `oauth_applications`, `oauth_access_grants` and `oauth_access_tokens`. `use_doorkeeper` draws its routes under `/oauth`: the consent screen at `/oauth/authorize`, `POST /oauth/token`, `/oauth/revoke`, `/oauth/introspect`, `/oauth/token/info`, the `/oauth/applications` client screens and the user's `/oauth/authorized_applications`. Doorkeeper has no login of its own, so `resource_owner_authenticator` is a block, run inside Doorkeeper's controllers, that returns the signed-in user or redirects to your sign-in page; the generated one raises until you replace it. A second block, `admin_authenticator`, guards the client screens, which answer 403 until you write it.
code
ruby · 18 lines# config/initializers/doorkeeper.rb
Doorkeeper.configure do
orm :active_record
# instance_eval'd inside Doorkeeper's own controllers
resource_owner_authenticator do
Session.find_by(id: cookies.signed[:session_id])&.user || begin
session[:return_to_after_authenticating] = request.url
redirect_to new_session_url
end
end
# guards /oauth/applications; the default answers 403
admin_authenticator do
member = Session.find_by(id: cookies.signed[:session_id])&.user
head :forbidden unless member&.admin?
end
endgo deeper
Recall the two generators, the use_doorkeeper route line and the /oauth paths it draws, and that resource_owner_authenticator must return the signed-in member or redirect.
Explain that the block is instance_eval'd in Doorkeeper's own controllers, which inherit base_controller rather than your ApplicationController, and how skip_controllers trims the routes.
Show production habits: close or skip the client-registration screens, always halt with a redirect when nobody is signed in, and read bin/rails routes -g oauth after each change.
Weigh self-service client registration against curating third-party clients by hand, and decide who owns approving each client and the scopes it may ask for.
## What Doorkeeper adds to a Rails app **Doorkeeper** is a Rails engine that makes your application an **OAuth 2 authorization server**. Other applications (the *clients*) send a member to your site to approve access, receive an authorization code, swap it for an access token at your token endpoint, and then call your API with that token. On a running-club platform, a third-party training app that wants to read a member's workouts gets a token for exactly that, and the member's password never leaves your site. Doorkeeper does **not** sign anyone in. It relies on the sign-in you already have (the Rails authentication generator, Devise or your own code) to say who the **resource owner** is, and that hand-off is the one block you must write before anything works. ## The generators Setup is two generators and a migration run: | Command | What it writes | |---|---| | `bin/rails generate doorkeeper:install` | `config/initializers/doorkeeper.rb`, `config/locales/doorkeeper.en.yml`, and a `use_doorkeeper` line in `config/routes.rb` | | `bin/rails generate doorkeeper:migration` | `db/migrate/..._create_doorkeeper_tables.rb` with `oauth_applications`, `oauth_access_grants` and `oauth_access_tokens` | | `bin/rails generate doorkeeper:pkce` | optional: `code_challenge` and `code_challenge_method` columns on `oauth_access_grants` | | `bin/rails generate doorkeeper:views` | optional: copies the consent and admin templates into `app/views` for editing | Then `bin/rails db:migrate`. The install generator alone leaves you with routes that point at tables that do not exist yet. ## What use_doorkeeper draws `use_doorkeeper` is a routing macro Doorkeeper adds to the Rails router. By default everything sits under `/oauth`: - `GET /oauth/authorize` shows the consent screen (`Doorkeeper::AuthorizationsController#new`); `POST` approves and `DELETE` denies. - `POST /oauth/token` is the token endpoint (`Doorkeeper::TokensController#create`). - `POST /oauth/revoke`, plus `POST /oauth/introspect` unless introspection is switched off with `allow_token_introspection false`. - `GET /oauth/token/info` describes the token presented. - `/oauth/applications` is a full set of screens for registering clients. - `/oauth/authorized_applications` lists the apps the signed-in member approved, with a revoke button. The block form changes the set: `skip_controllers :applications, :authorized_applications` leaves those screens out, `controllers authorizations: "oauth/consents"` swaps in your own subclass, and `use_doorkeeper scope: "api/oauth"` moves the prefix. `bin/rails routes -g oauth` shows the result. ## resource_owner_authenticator This block is the bridge to your sign-in. Doorkeeper runs it with `instance_eval` inside its own controllers, so `session`, `cookies`, `request` and `redirect_to` are all available. It must do one of two things: 1. **Return the signed-in user**, whose id is then written to grants and tokens as `resource_owner_id`. 2. **Halt the request**, normally by redirecting to your sign-in page and remembering where to come back to. The generated block raises `"Please configure doorkeeper resource_owner_authenticator block..."` so you cannot forget it. Two details catch people: - Doorkeeper's controllers inherit `Doorkeeper.config.base_controller`, which defaults to `ActionController::Base` (`ActionController::API` when `api_only` is set), **not your `ApplicationController`**. Private helpers defined there, such as the authentication generator's `resume_session`, are not callable from the block. Look the member up directly, or set `base_controller "ApplicationController"` and accept that your own filters then run on Doorkeeper's screens too. - Returning `nil` without redirecting leaves Doorkeeper running with no member. Since 5.9.9 the authorized-applications screen answers 401 in that case instead of acting on token rows that have no owner; the real fix is still to redirect. ## admin_authenticator and registering clients The `/oauth/applications` screens are guarded by a second block, `admin_authenticator`. Its default logs a warning and answers **403 Forbidden**, so the screens are closed until you write it. Many providers never open them: they skip the controller and create each client from a console, a seed or their own admin page with `Doorkeeper::Application.create!(name:, redirect_uri:, scopes:)`, which fills `uid` and `secret` in a `before_validation` callback. ## One approval, end to end Tracing a single approval shows where each piece acts: 1. The training app sends the member's browser to `/oauth/authorize?client_id=...&redirect_uri=...&response_type=code&scope=read_workouts`. 2. `Doorkeeper::AuthorizationsController` runs `authenticate_resource_owner!`, which calls your block. A signed-out member is redirected to sign in, and returns to the same URL if the block stored it. 3. The consent screen names the client and the requested scopes. Approving posts to `/oauth/authorize`, which saves a row in `oauth_access_grants` and redirects to the client's `redirect_uri` with a short-lived `code`. 4. The client's server posts that code to `/oauth/token` and receives an access token, saved in `oauth_access_tokens` with the member's id as `resource_owner_id`. 5. The client calls your API with the token, and your controllers check it with `doorkeeper_authorize!`. Only step 2 depends on code you wrote; everything else is Doorkeeper's. ## Common misreadings - **"install does everything."** It writes no migration. - **"Doorkeeper has its own login."** It only asks your block who is signed in. - **"An unconfigured admin block means an open admin."** It means a 403.
- Why can't resource_owner_authenticator call a private helper you defined in ApplicationController?Doorkeeper's controllers inherit `Doorkeeper.config.base_controller`, which defaults to `ActionController::Base` (`ActionController::API` under `api_only`), not your `ApplicationController`, and the block is `instance_eval`ed inside them. Look the member up directly, for example from `cookies.signed[:session_id]`, or set `base_controller "ApplicationController"` so your helpers are inherited, knowing your own `before_action` filters then run on the consent screen too.
- How do you register a third-party client if you skip the /oauth/applications screens?Create it from a console, a seed or your own admin page: `Doorkeeper::Application.create!(name: "PaceLab", redirect_uri: "https://pacelab.example/oauth/callback", scopes: "read_workouts")`. Doorkeeper fills `uid` and `secret` before validation; hand both to the client over a secure channel. Pass `confidential: false` for a mobile or single-page client that cannot keep a secret.
- doorkeeper:install also writes the oauth_* tables, so only db:migrate is left.
- use_doorkeeper draws only the token endpoint; you build the consent screen yourself.
- Doorkeeper signs members in itself, so the app needs no sign-in of its own.
- resource_owner_authenticator runs inside your own ApplicationController by default.
- Leaving admin_authenticator unset leaves /oauth/applications open to every visitor.
Assumes Doorkeeper 5.9 on Rails 8.1 with the authentication generator; the 401 from the authorized-applications screen for a nil resource owner arrived in 5.9.9.