With Doorkeeper, what does before_action -> { doorkeeper_authorize! :read_workouts, :write_workouts } let through, and what does a refused request receive?
answer
- token looked up on every request
- listed scopes are any-of
- no arguments means default_scopes
- 401 invalid_token versus 403 insufficient_scope
- doorkeeper_token.resource_owner_id names the member
basics
~20 sDoorkeeper's doorkeeper_authorize! passes a request whose access token exists, is unexpired and unrevoked, and carries at least one listed scope; a missing or dead token gets 401, a live token with none of the scopes gets 403.
solid answer
~40 s`doorkeeper_authorize!` reads the token through `doorkeeper_token` (by default from the `Authorization: Bearer` header, then the `access_token` or `bearer_token` param) and looks it up in `oauth_access_tokens`. No token, an unknown one, or an expired or revoked one answers **401** with `invalid_token`. A live token carrying **none** of the listed scopes answers **403** with `insufficient_scope`. The list is any-of: a token with only `read_workouts` passes `doorkeeper_authorize! :read_workouts, :write_workouts`; to require both, use two `before_action` lines. With no arguments it checks `default_scopes`, and if none are configured any live token passes. The refusal is a bodiless `head` plus a `WWW-Authenticate` header unless you override `doorkeeper_unauthorized_render_options` or set `handle_auth_errors :raise`. Inside the action, `doorkeeper_token.resource_owner_id` identifies the member, and it is `nil` for a client-credentials token.
code
ruby · 23 linesclass Api::WorkoutsController < ActionController::API
before_action -> { doorkeeper_authorize! :read_workouts }, only: %i[index show]
before_action -> { doorkeeper_authorize! :write_workouts }, only: :create
before_action :require_member
def index
render json: current_member.workouts.order(started_at: :desc).limit(50)
end
private
def require_member
head :forbidden unless doorkeeper_token.resource_owner_id
end
def current_member
@current_member ||= User.find(doorkeeper_token.resource_owner_id)
end
def doorkeeper_unauthorized_render_options(error: nil)
{ json: error.body }
end
endgo deeper
Recall that doorkeeper_authorize! guards an API action from a before_action, that it reads the Bearer token, and that the member comes from doorkeeper_token.resource_owner_id.
Explain the any-of scope check, the default_scopes fallback when no arguments are passed, and why a dead token gets 401 while a live one lacking the scope gets 403.
Show you have met the edges: owner-less client-credentials tokens, two filters to demand two scopes, and JSON errors through the render-options hooks or handle_auth_errors :raise.
Discuss how fine-grained scopes should be for third-party clients, and where a scope check ends and per-record authorization in a policy layer has to take over.
## Where the helper comes from Doorkeeper's engine includes `Doorkeeper::Rails::Helpers` into every controller through `ActiveSupport.on_load(:action_controller)`, a hook that both `ActionController::Base` and `ActionController::API` run. Any controller, HTML or API-only, therefore has three methods: `doorkeeper_authorize!`, `doorkeeper_token` and `valid_doorkeeper_token?`. You almost always call the first from a `before_action`, so a refusal stops the action from running. ## What one call checks 1. **The required scopes.** The arguments you pass, or `Doorkeeper.config.default_scopes` when you pass none. 2. **The token.** `doorkeeper_token` calls `Doorkeeper::OAuth::Token.authenticate` with the configured `access_token_methods`, by default `:from_bearer_authorization`, `:from_access_token_param` and `:from_bearer_param`, and finds the row with `by_token`. The result is memoised in `@doorkeeper_token` on the controller instance, which Rails builds fresh for each request. 3. **The verdict.** The token must be `acceptable?`: `accessible?` (neither expired nor revoked, checked on every call) and `includes_scope?` for the required list. 4. **The refusal**, if any, rendered before the action runs. ## Any-of, not all-of `includes_scope?` passes when **any** required scope is on the token (and when the required list is empty). On the running-club API: | Token scopes | Guard | Result | |---|---|---| | `read_workouts` | `doorkeeper_authorize! :read_workouts, :write_workouts` | passes | | `read_profile` | `doorkeeper_authorize! :read_workouts, :write_workouts` | 403 | | `read_profile` | `doorkeeper_authorize!` with `default_scopes :read_profile` | passes | | anything | `doorkeeper_authorize!` with no `default_scopes` | passes if live | To demand two scopes, stack two filters, `before_action -> { doorkeeper_authorize! :read_workouts }` and `before_action -> { doorkeeper_authorize! :write_workouts }`. Calling the helper twice inside one lambda goes wrong when both checks fail: the second refusal tries to respond again and Rails raises `AbstractController::DoubleRenderError`. ## What a refused request receives | Case | Status | `error` | Exception under `handle_auth_errors :raise` | |---|---|---|---| | no token, or unknown | 401 | `invalid_token` | `Doorkeeper::Errors::TokenUnknown` | | expired | 401 | `invalid_token` | `Doorkeeper::Errors::TokenExpired` | | revoked | 401 | `invalid_token` | `Doorkeeper::Errors::TokenRevoked` | | live, none of the scopes | 403 | `insufficient_scope` | `Doorkeeper::Errors::TokenForbidden` | By default Doorkeeper merges `Cache-Control` and a `WWW-Authenticate: Bearer realm="Doorkeeper", error=...` header into the response and calls `head` with the status, so the body is empty. Two hooks change that: - Define `doorkeeper_unauthorized_render_options(error: nil)` and `doorkeeper_forbidden_render_options(error: nil)` in the controller and return render options such as `{ json: error.body }`; Doorkeeper adds the status. Returning `respond_not_found_when_forbidden: true` from the forbidden hook turns the 403 into a 404. - Set `handle_auth_errors :raise` and `rescue_from Doorkeeper::Errors::InvalidToken`. All four classes above inherit from it, `TokenForbidden` included. You then build the whole response, headers included, yourself. ## Finding the member, and the client-credentials trap The action identifies the member through `doorkeeper_token.resource_owner_id`, the id your `resource_owner_authenticator` returned when the member approved the client. The usual helper is `User.find(doorkeeper_token.resource_owner_id)`. A token issued by the **client credentials** grant belongs to the client alone, so its `resource_owner_id` is `nil`. If the client's registered scopes allow it, such a token passes `doorkeeper_authorize! :read_workouts`, and `User.find(nil)` then raises `ActiveRecord::RecordNotFound`. Guard member-only endpoints explicitly, or keep machine clients away from member scopes with `scopes_by_grant_type`. ## Narrowing where tokens come from `access_token_methods :from_bearer_authorization` makes Doorkeeper ignore tokens in parameters. Since 5.9.7 a request presenting a token by more than one method is refused as tokenless, but a token in the query string alone is still accepted under the default list. ## Testing the guard A request test needs a real token row, which is quick to build because Doorkeeper fills the token value itself: 1. Create a client with `Doorkeeper::Application.create!(name: "PaceLab", redirect_uri: "https://pacelab.example/cb")`. 2. Create a token with `Doorkeeper::AccessToken.create!(application: app, resource_owner_id: member.id, scopes: "read_workouts")`; `plaintext_token` on that object holds the value to send. 3. Call `get api_workouts_path, headers: { "Authorization" => "Bearer #{token.plaintext_token}" }` and assert 200. 4. Repeat with a token scoped `read_profile` and assert 403, and with `token.revoke` called first and assert 401. Covering all three answers pins down the any-of rule, the scope refusal and the liveness check in one place, so a later change to `default_scopes` or to the filters shows up as a failing test rather than an open endpoint. ## Common misreadings - **"The list means all of these."** It means any one of them. - **"No arguments means no scope check."** It means the default scopes, when any are configured. - **"A valid token always has a member."** Client-credentials tokens do not.
- How do you make an action require both read_workouts and write_workouts?Stack two filters: `before_action -> { doorkeeper_authorize! :read_workouts }` and `before_action -> { doorkeeper_authorize! :write_workouts }`. A refusal from the first responds and halts the callback chain, so the second never runs on a rejected request. Two calls inside one lambda break when both fail, because the second refusal responds again and Rails raises `AbstractController::DoubleRenderError`.
- How do you return a JSON error body instead of Doorkeeper's empty 401?Override `doorkeeper_unauthorized_render_options(error: nil)` (and `doorkeeper_forbidden_render_options` for 403) to return render options such as `{ json: error.body }`; Doorkeeper still sets the status and `WWW-Authenticate`. Alternatively set `handle_auth_errors :raise` and `rescue_from Doorkeeper::Errors::InvalidToken`, which also catches `TokenForbidden`, then build the response and its headers yourself.
- Can the API refuse tokens sent as an access_token query parameter?Yes: set `access_token_methods :from_bearer_authorization` in the initializer. The default list also reads the `access_token` and `bearer_token` params. Since 5.9.7 a request carrying a token by two methods is refused with 401, but a token in the query string alone is accepted until you narrow the list.
A venue door with a list of accepted wristband colours: show any one colour on the list and you are in. To require two colours you post two doormen in a row, each checking one.
- doorkeeper_authorize! :a, :b requires the token to carry both scopes.
- With no arguments, doorkeeper_authorize! requires one of the optional_scopes.
- Doorkeeper checks expiry only when issuing a token, not on each request.
- A live token missing the scope gets 401 invalid_token, like a bad token.
- Every token that passes doorkeeper_authorize! has a resource_owner_id.