Repository navigation
Migration from old versions
The intent of this document is to make migration of breaking changes as easy as possible. Please note that all breaking changes may not be included here. Please check the CHANGELOG.md for a full list of changes before finalizing the upgrade process.
Follow latest changes (specially backwards incompatible ones, we follow semantic versioning) in the CHANGELOG: https://github.com/doorkeeper-gem/doorkeeper/blob/main/CHANGELOG.md.
Authorization Server Metadata endpoint (#1838)
use_doorkeeper now also draws GET /.well-known/oauth-authorization-server (doorkeeper/metadata#show), outside the oauth scope. The response is built from your Doorkeeper configuration (RFC 8414).
Applications that already serve their own document at /.well-known/oauth-authorization-server, for example to advertise a registration_endpoint for dynamic client registration (RFC 7591). use_doorkeeper usually sits near the top of config/routes.rb, so Doorkeeper's route is drawn first and replaces yours. Nothing warns, and the app still boots.
Check with:
bin/rails routes | grep oauth-authorization-server
Choose one:
-
Keep your own endpoint and skip Doorkeeper's:
use_doorkeeper do skip_controllers :metadata end
skip_controllersreplaces the skip list each time it is called. It does not add to it. If you already skip other controllers, add:metadatato that same call:use_doorkeeper do skip_controllers :applications, :authorized_applications, :metadata end
-
Remove your own endpoint and use Doorkeeper's. Move any extra fields into
custom_metadata, and setissuer(it defaults to the request base URL):# config/initializers/doorkeeper.rb Doorkeeper.configure do issuer "https://auth.example.com" custom_metadata registration_endpoint: "https://auth.example.com/oauth/register" end
Client authentication registry (#1840)
Doorkeeper resolves client authentication at the token/revocation/introspection endpoints through a registry of named strategies (RFC 6749 §2.3) instead of the previous hard-coded basic/params lookup. This section collects the breaking changes, deprecations and migration steps for this change.
The new client_authentication config option declares which methods Doorkeeper accepts and the order in which they are tried:
Doorkeeper.configure do
# This is the default
client_authentication %i[client_secret_basic client_secret_post none]
endThe three built-in strategies are:
| Strategy | Description |
|---|---|
client_secret_basic |
Credentials in the HTTP Authorization: Basic header (RFC 6749 §2.3.1) |
client_secret_post |
Credentials (client_id/client_secret) in the request body |
none |
Public clients: a bare client_id in the request body, no secret |
You can register your own strategy with:
Doorkeeper::ClientAuthentication.register(:my_method, MyStrategy)A strategy responds to matches_request? and authenticate, returning a Doorkeeper::ClientAuthentication::Credentials. See Changing how clients are authenticated for the full contract.
The client_secret_post and none strategies now look at the request body only (request.request_parameters), per RFC 6749 §2.3.1 â sending secrets in a URI query is explicitly discouraged by the spec (secrets end up in server logs, proxies and browser history). This applies to every endpoint that authenticates clients: token, revocation (/oauth/revoke) and introspection (/oauth/introspect) â they all resolve client authentication through the same registry. Clients that passed client_id/client_secret in the query string of any of these endpoints will stop authenticating and must move the credentials into the request body (or use HTTP Basic).
A request that carries a non-blank Authorization header (e.g. a Bearer token, or a malformed Basic header) is attempting header-based authentication and is no longer silently treated as an unauthenticated public client the way the legacy from_params extractor did. Public clients must send their client_id in the request body without an Authorization header.
The class now lives at Doorkeeper::ClientAuthentication::Credentials. The old constant remains as a deprecated alias for one release (marked with deprecate_constant, so Ruby warns on access when deprecation warnings are enabled) so referencing code does not raise NameError â but its legacy .from_request / .from_basic / .from_params class methods are gone (extraction now goes through the registry). Update references to the new constant.
Both the array form (client_authentication %i[client_secret_basic client_secret_post none]) and the varargs form (client_authentication :client_secret_basic, :client_secret_post) are accepted, and nothing (in particular :none) is appended â a restrictive configuration is never silently broadened. A configuration that resolves to zero registered methods is logged as an error at boot instead of silently failing every client authentication.
The client_credentials config option is deprecated in favour of client_authentication. During the deprecation window the legacy values are mapped automatically:
| Legacy value | Mapped to |
|---|---|
:from_basic |
:client_secret_basic |
:from_params |
:client_secret_post (+ :none, see below) |
:none (public client support) is appended only when :from_params was configured â that is the only legacy method that accepted a bare client_id without a secret. A Basic-only configuration (client_credentials :from_basic) is therefore not silently broadened to accept public clients.
If both client_credentials and client_authentication are set, client_authentication wins and Doorkeeper warns about the conflict at boot.
A callable passed to client_credentials (e.g. client_credentials ->(request) { [client_id, client_secret] }) is wrapped in a legacy adapter (Doorkeeper::ClientAuthentication::LegacyCallable) so it keeps working during the deprecation window. Migrate it to a registered strategy via Doorkeeper::ClientAuthentication.register before the client_credentials option is removed.
Doorkeeper.config.client_credentials_methods has been renamed to client_authentication_methods. The old name remains as a delegating alias that emits a one-shot deprecation warning. The alias returns the legacy method-name symbols (e.g. :from_basic, :from_params) rather than the internal Method objects, so external consumers such as doorkeeper-openid_connect (which map those symbols in token_endpoint_auth_methods_supported) keep working unchanged for one release.
-
Audit your clients: if any of them send
client_id/client_secretin the token endpoint query string, switch them to the request body or HTTP Basic before upgrading. -
Update your initializer: replace
client_credentials :from_basic, :from_paramswithclient_authentication %i[client_secret_basic client_secret_post none](dropnoneif you don't serve public clients). -
Migrate custom callables: if you passed a lambda/proc to
client_credentials, rewrite it as a strategy class and register it withDoorkeeper::ClientAuthentication.register, then reference it by name inclient_authentication. -
Update constant references:
Doorkeeper::OAuth::Client::CredentialsâDoorkeeper::ClientAuthentication::Credentials. -
Update config readers:
Doorkeeper.config.client_credentials_methodsâDoorkeeper.config.client_authentication_methods. -
Check public clients: make sure they send a bare
client_idin the request body with noAuthorizationheader â requests with a stray non-blank header are now rejected.
Fallback secret upgrade race fix (#1923)
When a fallback secret strategy is configured (hash_application_secrets / hash_token_secrets with fallback:), a credential that matches in the fallback format is automatically re-stored in the current format. On Active Record this upgrade now uses a conditional update_all instead of #update. This fixes a race condition where a concurrent #renew_secret could be silently undone by a stale upgrade write, leaving the superseded secret valid (pre-existing since fallback secrets were introduced in v5.1.0).
- The upgrade writes only while the column still holds the value that matched (and, under optimistic locking, the lock version the instance was read with). A lost race skips the upgrade instead of overwriting the new secret; the credential stays in the fallback format and is upgraded by whichever authentication comes next.
- The write is a single
update_allstatement, so model callbacks and validations no longer run on this path, and other unsaved changes on the instance are not written along with it. Timestamps (updated_at/updated_on, honouringrecord_timestamps) and optimistic locking are still maintained, and the instance is brought in step with the row afterwards. - The upgrade goes through two ORM hooks on the model class:
write_upgraded_secret(instance, attr, matched, upgraded), which returns whether the row was written, andrestore_matched_secret(instance, attr, matched), called when it was not. The default implementations preserve the historical#updatebehaviour, so ORM extensions (doorkeeper-mongodb, doorkeeper-sequel) behave exactly as before until they implement a conditional write in their own terms.
None for most applications. If you rely on model callbacks or validations running when a fallback secret is upgraded on match (e.g. an after_update on Doorkeeper::Application, AccessToken or AccessGrant that observes the secret column), be aware that the Active Record upgrade path no longer triggers them. Applications without a fallback strategy never reach this path.
private_key_jwt audience is built from the server's own identity (#1926)
private_key_jwt client authentication (opt-in, added in 6.0.0.beta2 by #1896) checks the aud claim of a client assertion against the audiences this server accepts. Those audiences are now derived only from the server's configured identity â the issuer option or Rails.application.routes.default_url_options[:host] â and never from the request's Host header. The audience is the claim that ties an assertion to one authorization server, so it cannot come from a value the caller controls; previously, a server with neither option configured built the endpoint URLs from the incoming request, which allowed an assertion minted for another authorization server to be replayed against it.
-
The acceptable audiences are the
issuerstring (when set), the URL of the endpoint being called and the token endpoint URL â the two URLs built fromdefault_url_options[:host], or fromissuerwhen it is an absolute URL. TheHost/X-Forwarded-Hostheaders are no longer consulted. -
A server that enables
private_key_jwtbut configures neitherissuernordefault_url_options[:host]has no acceptable audience and refuses every client assertion withinvalid_client(401). Doorkeeper reports this at boot with an error-level log line:[DOORKEEPER] private_key_jwt client authentication is enabled, but the server identifies itself nowhere, so no audience is acceptable and every client assertion will be refused. Configure issuer, or Rails.application.routes.default_url_options[:host]. -
The audience is decided before the client is looked up, so such a server refuses without fetching the client's
jwks_uri.
Only deployments that list :private_key_jwt in client_authentication and set neither issuer nor Rails.application.routes.default_url_options[:host]. Deployments on the default client authentication methods, or that already configure either option, are not affected.
-
Give the server an identity. Either option is enough;
issueris the one the Authorization Server Metadata endpoint (RFC 8414) and RFC 9207 already use, so it is the natural choice:# config/initializers/doorkeeper.rb Doorkeeper.configure do issuer "https://auth.example.com" end
or
# config/environments/production.rb Rails.application.routes.default_url_options[:host] = "auth.example.com"
Action Mailer's
config.action_mailer.default_url_optionsis a separate setting and is not consulted. -
Make sure the identity matches what your clients already send as
aud: the token endpoint URL (https://auth.example.com/oauth/token, per OIDC Core §9) or the issuer identifier. Anissuerthat is not an absolute URL is accepted as an audience literally, but then no endpoint URL can be derived from it, so clients sending the token endpoint URL still needdefault_url_options[:host]. -
Check the boot log after deploying: the
[DOORKEEPER] private_key_jwt client authentication is enabled, but the server identifies itself nowhereline means assertions are being refused.
No change is needed on the client side. Once the server's identity matches the aud value clients already send, private_key_jwt authentication resumes.
- Starting from 5.9.1 several I18n colons are no longer hardcoded in the views â they are now part of the translation strings. If you have customized Doorkeeper views and/or changed translations - see (#1809)[https://github.com/doorkeeper-gem/doorkeeper/pull/1809/changes] for more details.
-
Starting from Doorkeeper 5.5 client authentication for Resource Owner Password Grant is required as stated in OAuth RFC.
[IMPORTANT] you need to create a new OAuth client (Doorkeeper::Application) if you didn't have it before and use client credentials in HTTP Basic auth if you previously used this grant flow without client authentication. For migration purposes you could enable skip_client_authentication_for_password_grant configuration option to true, but such behavior (as well as configuration option) would be completely removed in a future version of Doorkeeper. All the users of your provider application now need to include client credentials when they use this grant flow.
-
Token revocation endpoint now requires strict client authentication as required by the RFC 7009. So clients need to send
client_id(in case of public clients) andclient_id&client_secret(for private clients).Please take a look at section 2.1. Revocation Request of the RFC7009 and then section 2.3. Client Authentication of RFC6749 with section 5. Security Considerations of RFC7009 to get more info on how you could implement authentication (via HTTP Auth header or via params which is not recommended).
-
Doorkeeper now supports polymorphic resource owners (if configured), so internals were changes to pass
resource ownerinstance across the methods and objects, not just it's ID. So if you have some patches for Doorkeeper internals - you need to change them. See #1355 for details. -
Doorkeeper built-in Application views not strictly set
asoption equal todoorkeeper_applicationforform_for. If you previously changed it on your custom views or overridden controller - make sure you didn't break something.
- Return error message properly, add descriptive
error_descriptionforinvalid_requesterror:
# invalid_request error message
# config/locales/en.yml
invalid_request:
unknown: 'The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed.'
missing_param: 'Missing required parameter: %{value}.'
not_support_pkce: 'Invalid code_verifier parameter. Server does not support pkce.'
request_not_authorized: 'Request need to be authorized. Required parameter for authorizing request is missing or invalid.'- As RFC6749#section-3.3,
scopeparam need to be provided at authorization request in case server doesn't defineddefault_scope--> Change column attribute:scopesofoauth_access_grants(table that saving authorization_code) MUST NOT be null. See https://stackoverflow.com/a/58714209/10780636 for details - Change made at:
lib/generators/doorkeeper/templates/migration.rb.erbOf theoauth_access_grantstable, changescopesto null: false, default: ''
-
native_redirect_urioption is deprecated now and will be removed soon (see more details here #1238).
- Error responses now return a 400 HTTP status by default (previously 401), and a 401 only for
invalid_clientandinvalid_tokenerrors. - Those who defined
custom_access_token_expires_inconfiguration option need to check their block implementation: if you are callingoauth_client.applicationto getDoorkeeper::Applicationinstance of your client application, then you need to replace it with justoauth_client. -
[IMPORTANT]: Doorkeeper access token value, client secrets and so on now has more complexity. It may have possible side-effects in case you have custom database constraints for access token value / application secrets / refresh tokens or you patched Doorkeeper models and introduced token value validations, or you are using database with case-insensitive
WHEREclause like MySQL (in this case you can face some collisions). Doorkeeper < 5.1.x access token value matched[a-f0-9]regex, and now it matches[a-zA-Z0-9\-_]. In case you have some db restrictions and you don't use custom token generator please change configuration optiondefault_generator_methodinconfig/initializers/doorkeeper.rbto:hex.
-
Doorkeeper::Applicationnow has a new boolean column namedconfidentialthat istrueby default and hasNOT NULL CONSTRAINT. This column is required to allow creating Public & Private Clients as mentioned in Section 8.5 of draft-ietf-oauth-native-apps-12 of OAuth 2 RFC which was previously unavailable. If you are migrating from the Doorkeeper <= 5.0, then you can easily add this column by generating a proper migration file using the following command:rails generate doorkeeper:confidential_applications.[IMPORTANT]: all the applications (clients) starting from 5.0 / 4.4.x releases are considered as private by default. You need to manually change
confidentialcolumn tofalseif you are using public clients, otherwise your mobile or other applications will not be able to authorize. See #1142 for more details.
-
[IMPORTANT]: Doorkeeper JSON responses changed:
scopesfield was replaced withscope,expires_in_secondstoexpires_into be consistent and match the RFC. -
Doorkeeper#configured?,Doorkeeper#database_installed?, andDoorkeeper#installed?methods were removed, so any Doorkeeper ORM extension doesn't need to support these methods starting from 5.0. - Many memoized and other instance variables (like
@tokenindoorkeeper_tokenmethod forDoorkeeper::Helpers::Controller) were renamed during refactoring, so if you are using them â just don't do it and call the original methods (helpers, etc) in order to get the required value. - Test suite now has a refactored infrastructure:
spec_helper_integrationnow renamed to industry-standardspec_helper. -
custom_access_token_expires_inoption now provides aDoorkeeper::OAuth::Authorization::Contextobject (|context|) instead of raw params (|client, grant_type, scopes|). The context object has all these variables and you can access them in the block (likecontext.grant_typeorcontext.client). -
admin_authenticatorblock now returns "403 Forbidden" response by default if developer didn't declare another behavior explicitly. - Previously authorization code response route was
/oauth/authorize/<code>, now it isoauth/authorize/native?code=<code>(in order to help applications to automatically find the code value).
- Bootstrap CSS was updated from 3.x to 4.0.
-
[IMPORTANT]: 4.4.x release includes backport security fix from 5.x for token revocation when using public clients, so starting from this version all the applications (clients) are considered as private by default. You need to manually change
confidentialcolumn tofalseif you are using public clients, otherwise your mobile (or other) applications will not be able to authorize. See #1142 for more details.
- FactoryGirl changed to FactoryBot.
- Previously authorization code response route was
/oauth/authorize/<code>, now it isoauth/authorize/native?code=<code>(in order to help applications to automatically find the code value).
- MongoDB adapter extracted to its own extension.
-
doorkeeper_unauthorized_render_options(error:)anddoorkeeper_forbidden_render_options(error:)now accepterrorkeyword argument.
- Added
scopescolumn to applications. Add it withrails generate doorkeeper:application_scopesgenerator.
-
doorkeeper_forDSL was changed tobefore_action :dorkeeper_authorize!. -
test_redirect_urioption renamed tonative_redirect_uri. -
mount Doorkeeper::Enginenow replaced withuse_doorkeeperroutes helper.
Doorkeeper is not an isolated engine anymore. Which means that most of the paths and old related engine methods won't work. Here's a list of things that changed:
-
mount Doorkeeper::Enginewon't work. Replace it withuse_doorkeeperin yourconfig/routes.rbfile. - All route paths have changed. If you generated all views, or use custom ones, you'll have to prepend
oauth_to each of them:
# also applies to prefixes (edit_ and new_)
authorized_applications(_path|_url) => oauth_authorized_applications(_path|_url)
applications(_path|_url) => oauth_applications(_path|_url)
authorization(_path|_url) => oauth_authorization(_path|_url)- The locale file has been updated. You'll need to reinstall the file with
rails g doorkeeper:install(ignore other existing files) to ensure the gem works properly. - Authorization code is now configurable:
authorization_code_expires_in 10.minutesThe column resource_owner_id accepts null values, since we now support the Client Credentials flow.
change_column :oauth_access_tokens, :resource_owner_id, :integer, :null => trueTwo things were changed in scopes
- The configuration for scopes has changed. You now have to use
default_scopesandoptional_scopesinstead of theauthorization_scopesblock:
Doorkeeper.configure do
default_scopes :public
optional_scopes :write, :update
end- You have to translate your scopes in your application's locale file(s).
en:
doorkeeper:
scopes:
public: "Access your public data"
write: "Update your data"Add indexes to database:
class UpgradeToVersion03 < ActiveRecord::Migration
def change
add_index :oauth_applications, :uid, :unique => true
add_index :oauth_access_grants, :token, :unique => true
add_index :oauth_access_tokens, :token, :unique => true
add_index :oauth_access_tokens, :resource_owner_id
add_index :oauth_access_tokens, :refresh_token, :unique => true
end
end-
doorkeeper_fordoes not accept the:alloption anymore. -
doorkeeper_foronly accepts:exceptoption when:allwas specified.
class UpgradeToVersion02 < ActiveRecord::Migration
def change
add_column :oauth_access_grants, :scopes, :string
# If you are upgrading from version 0.1.0, uncomment the line below.
# add_column :oauth_access_grants, :revoked_at, :datetime
add_column :oauth_access_tokens, :refresh_token, :string
add_column :oauth_access_tokens, :scopes, :string
add_column :oauth_access_tokens, :expires_in, :integer
remove_column :oauth_access_tokens, :expires_at
end
end