]> git.openstreetmap.org Git - rails.git/blob - config/initializers/doorkeeper.rb
a96e6fd6c68ea28bdb39e7a9c4f34a0949f4dc38
[rails.git] / config / initializers / doorkeeper.rb
1 # frozen_string_literal: true
2
3 Doorkeeper.configure do
4   # Change the ORM that doorkeeper will use (requires ORM extensions installed).
5   # Check the list of supported ORMs here: https://github.com/doorkeeper-gem/doorkeeper#orms
6   orm :active_record
7
8   # This block will be called to check whether the resource owner is authenticated or not.
9   resource_owner_authenticator do
10     current_user
11   end
12
13   # If you didn't skip applications controller from Doorkeeper routes in your application routes.rb
14   # file then you need to declare this block in order to restrict access to the web interface for
15   # adding oauth authorized applications. In other case it will return 403 Forbidden response
16   # every time somebody will try to access the admin web interface.
17
18   admin_authenticator do
19     current_user
20   end
21
22   # You can use your own model classes if you need to extend (or even override) default
23   # Doorkeeper models such as `Application`, `AccessToken` and `AccessGrant.
24   #
25   # Be default Doorkeeper ActiveRecord ORM uses it's own classes:
26   #
27   # access_token_class "Doorkeeper::AccessToken"
28   # access_grant_class "Doorkeeper::AccessGrant"
29   # application_class "Doorkeeper::Application"
30   #
31   # Don't forget to include Doorkeeper ORM mixins into your custom models:
32   #
33   #   *  ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessToken - for access token
34   #   *  ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessGrant - for access grant
35   #   *  ::Doorkeeper::Orm::ActiveRecord::Mixins::Application - for application (OAuth2 clients)
36   #
37   # For example:
38   #
39   # access_token_class "MyAccessToken"
40   #
41   # class MyAccessToken < ApplicationRecord
42   #   include ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessToken
43   #
44   #   self.table_name = "hey_i_wanna_my_name"
45   #
46   #   def destroy_me!
47   #     destroy
48   #   end
49   # end
50
51   application_class "Oauth2Application"
52
53   # Enables polymorphic Resource Owner association for Access Tokens and Access Grants.
54   # By default this option is disabled.
55   #
56   # Make sure you properly setup you database and have all the required columns (run
57   # `bundle exec rails generate doorkeeper:enable_polymorphic_resource_owner` and execute Rails
58   # migrations).
59   #
60   # If this option enabled, Doorkeeper will store not only Resource Owner primary key
61   # value, but also it's type (class name). See "Polymorphic Associations" section of
62   # Rails guides: https://guides.rubyonrails.org/association_basics.html#polymorphic-associations
63   #
64   # [NOTE] If you apply this option on already existing project don't forget to manually
65   # update `resource_owner_type` column in the database and fix migration template as it will
66   # set NOT NULL constraint for Access Grants table.
67   #
68   # use_polymorphic_resource_owner
69
70   # If you are planning to use Doorkeeper in Rails 5 API-only application, then you might
71   # want to use API mode that will skip all the views management and change the way how
72   # Doorkeeper responds to a requests.
73   #
74   # api_only
75
76   # Enforce token request content type to application/x-www-form-urlencoded.
77   # It is not enabled by default to not break prior versions of the gem.
78
79   enforce_content_type
80
81   # Authorization Code expiration time (default: 10 minutes).
82   #
83   # authorization_code_expires_in 10.minutes
84
85   # Access token expiration time (default: 2 hours).
86   # If you want to disable expiration, set this to `nil`.
87
88   access_token_expires_in nil
89
90   # Assign custom TTL for access tokens. Will be used instead of access_token_expires_in
91   # option if defined. In case the block returns `nil` value Doorkeeper fallbacks to
92   # +access_token_expires_in+ configuration option value. If you really need to issue a
93   # non-expiring access token (which is not recommended) then you need to return
94   # Float::INFINITY from this block.
95   #
96   # `context` has the following properties available:
97   #
98   #   * `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
99   #   * `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
100   #   * `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
101   #   * `resource_owner` - authorized resource owner instance (if present)
102   #
103   # custom_access_token_expires_in do |context|
104   #   context.client.additional_settings.implicit_oauth_expiration
105   # end
106
107   # Use a custom class for generating the access token.
108   # See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-access-token-generator
109   #
110   # access_token_generator '::Doorkeeper::JWT'
111
112   # The controller +Doorkeeper::ApplicationController+ inherits from.
113   # Defaults to +ActionController::Base+ unless +api_only+ is set, which changes the default to
114   # +ActionController::API+. The return value of this option must be a stringified class name.
115   # See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-controllers
116
117   base_controller "ApplicationController"
118
119   # Reuse access token for the same resource owner within an application (disabled by default).
120   #
121   # This option protects your application from creating new tokens before old valid one becomes
122   # expired so your database doesn't bloat. Keep in mind that when this option is `on` Doorkeeper
123   # doesn't updates existing token expiration time, it will create a new token instead.
124   # Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383
125   #
126   # You can not enable this option together with +hash_token_secrets+.
127
128   reuse_access_token
129
130   # In case you enabled `reuse_access_token` option Doorkeeper will try to find matching
131   # token using `matching_token_for` Access Token API that searches for valid records
132   # in batches in order not to pollute the memory with all the database records. By default
133   # Doorkeeper uses batch size of 10 000 records. You can increase or decrease this value
134   # depending on your needs and server capabilities.
135   #
136   # token_lookup_batch_size 10_000
137
138   # Set a limit for token_reuse if using reuse_access_token option
139   #
140   # This option limits token_reusability to some extent.
141   # If not set then access_token will be reused unless it expires.
142   # Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/1189
143   #
144   # This option should be a percentage(i.e. (0,100])
145   #
146   # token_reuse_limit 100
147
148   # Only allow one valid access token obtained via client credentials
149   # per client. If a new access token is obtained before the old one
150   # expired, the old one gets revoked (disabled by default)
151   #
152   # When enabling this option, make sure that you do not expect multiple processes
153   # using the same credentials at the same time (e.g. web servers spanning
154   # multiple machines and/or processes).
155   #
156   # revoke_previous_client_credentials_token
157
158   # Hash access and refresh tokens before persisting them.
159   # This will disable the possibility to use +reuse_access_token+
160   # since plain values can no longer be retrieved.
161   #
162   # Note: If you are already a user of doorkeeper and have existing tokens
163   # in your installation, they will be invalid without adding 'fallback: :plain'.
164   #
165   # hash_token_secrets
166   # By default, token secrets will be hashed using the
167   # +Doorkeeper::Hashing::SHA256+ strategy.
168   #
169   # If you wish to use another hashing implementation, you can override
170   # this strategy as follows:
171
172   hash_token_secrets :using => "::Doorkeeper::SecretStoring::Plain",
173                      :fallback => "::Doorkeeper::SecretStoring::Sha256Hash"
174
175   # Keep in mind that changing the hashing function will invalidate all existing
176   # secrets, if there are any.
177
178   # Hash application secrets before persisting them.
179
180   hash_application_secrets
181
182   # By default, applications will be hashed
183   # with the +Doorkeeper::SecretStoring::SHA256+ strategy.
184   #
185   # If you wish to use bcrypt for application secret hashing, uncomment
186   # this line instead:
187   #
188   # hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt'
189
190   # When the above option is enabled, and a hashed token or secret is not found,
191   # you can allow to fall back to another strategy. For users upgrading
192   # doorkeeper and wishing to enable hashing, you will probably want to enable
193   # the fallback to plain tokens.
194   #
195   # This will ensure that old access tokens and secrets
196   # will remain valid even if the hashing above is enabled.
197   #
198   # This can be done by adding 'fallback: plain', e.g. :
199   #
200   # hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt', fallback: :plain
201
202   # Issue access tokens with refresh token (disabled by default), you may also
203   # pass a block which accepts `context` to customize when to give a refresh
204   # token or not. Similar to +custom_access_token_expires_in+, `context` has
205   # the following properties:
206   #
207   # `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
208   # `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
209   # `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
210   #
211   # use_refresh_token
212
213   # Provide support for an owner to be assigned to each registered application (disabled by default)
214   # Optional parameter confirmation: true (default: false) if you want to enforce ownership of
215   # a registered application
216   # NOTE: you must also run the rails g doorkeeper:application_owner generator
217   # to provide the necessary support
218
219   enable_application_owner :confirmation => true
220
221   # Define access token scopes for your provider
222   # For more information go to
223   # https://doorkeeper.gitbook.io/guides/ruby-on-rails/scopes
224
225   # default_scopes  :public
226   optional_scopes(*Oauth::SCOPES, *Oauth::PRIVILEGED_SCOPES)
227
228   # Allows to restrict only certain scopes for grant_type.
229   # By default, all the scopes will be available for all the grant types.
230   #
231   # Keys to this hash should be the name of grant_type and
232   # values should be the array of scopes for that grant type.
233   # Note: scopes should be from configured_scopes (i.e. default or optional)
234   #
235   # scopes_by_grant_type password: [:write], client_credentials: [:update]
236
237   # Forbids creating/updating applications with arbitrary scopes that are
238   # not in configuration, i.e. +default_scopes+ or +optional_scopes+.
239   # (disabled by default)
240
241   enforce_configured_scopes
242
243   # Change the way client credentials are retrieved from the request object.
244   # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
245   # falls back to the `:client_id` and `:client_secret` params from the `params` object.
246   # Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
247   # for more information on customization
248   #
249   # client_credentials :from_basic, :from_params
250
251   # Change the way access token is authenticated from the request object.
252   # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
253   # falls back to the `:access_token` or `:bearer_token` params from the `params` object.
254   # Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
255   # for more information on customization
256
257   access_token_methods :from_bearer_authorization
258
259   # Forces the usage of the HTTPS protocol in non-native redirect uris (enabled
260   # by default in non-development environments). OAuth2 delegates security in
261   # communication to the HTTPS protocol so it is wise to keep this enabled.
262   #
263   # Callable objects such as proc, lambda, block or any object that responds to
264   # #call can be used in order to allow conditional checks (to allow non-SSL
265   # redirects to localhost for example).
266
267   force_ssl_in_redirect_uri do |uri|
268     !Rails.env.development? && uri.host != "127.0.0.1"
269   end
270
271   # Specify what redirect URI's you want to block during Application creation.
272   # Any redirect URI is whitelisted by default.
273   #
274   # You can use this option in order to forbid URI's with 'javascript' scheme
275   # for example.
276   #
277   # forbid_redirect_uri { |uri| uri.scheme.to_s.downcase == 'javascript' }
278
279   # Allows to set blank redirect URIs for Applications in case Doorkeeper configured
280   # to use URI-less OAuth grant flows like Client Credentials or Resource Owner
281   # Password Credentials. The option is on by default and checks configured grant
282   # types, but you **need** to manually drop `NOT NULL` constraint from `redirect_uri`
283   # column for `oauth_applications` database table.
284   #
285   # You can completely disable this feature with:
286   #
287   # allow_blank_redirect_uri false
288   #
289   # Or you can define your custom check:
290   #
291   # allow_blank_redirect_uri do |grant_flows, client|
292   #   client.superapp?
293   # end
294
295   # Specify how authorization errors should be handled.
296   # By default, doorkeeper renders json errors when access token
297   # is invalid, expired, revoked or has invalid scopes.
298   #
299   # If you want to render error response yourself (i.e. rescue exceptions),
300   # set +handle_auth_errors+ to `:raise` and rescue Doorkeeper::Errors::InvalidToken
301   # or following specific errors:
302   #
303   #   Doorkeeper::Errors::TokenForbidden, Doorkeeper::Errors::TokenExpired,
304   #   Doorkeeper::Errors::TokenRevoked, Doorkeeper::Errors::TokenUnknown
305   #
306   # handle_auth_errors :raise
307
308   # Customize token introspection response.
309   # Allows to add your own fields to default one that are required by the OAuth spec
310   # for the introspection response. It could be `sub`, `aud` and so on.
311   # This configuration option can be a proc, lambda or any Ruby object responds
312   # to `.call` method and result of it's invocation must be a Hash.
313   #
314   # custom_introspection_response do |token, context|
315   #   {
316   #     "sub": "Z5O3upPC88QrAjx00dis",
317   #     "aud": "https://protected.example.net/resource",
318   #     "username": User.find(token.resource_owner_id).username
319   #   }
320   # end
321   #
322   # or
323   #
324   # custom_introspection_response CustomIntrospectionResponder
325
326   # Specify what grant flows are enabled in array of Strings. The valid
327   # strings and the flows they enable are:
328   #
329   # "authorization_code" => Authorization Code Grant Flow
330   # "implicit"           => Implicit Grant Flow
331   # "password"           => Resource Owner Password Credentials Grant Flow
332   # "client_credentials" => Client Credentials Grant Flow
333   #
334   # If not specified, Doorkeeper enables authorization_code and
335   # client_credentials.
336   #
337   # implicit and password grant flows have risks that you should understand
338   # before enabling:
339   #   http://tools.ietf.org/html/rfc6819#section-4.4.2
340   #   http://tools.ietf.org/html/rfc6819#section-4.4.3
341
342   grant_flows %w[authorization_code]
343
344   # Allows to customize OAuth grant flows that +each+ application support.
345   # You can configure a custom block (or use a class respond to `#call`) that must
346   # return `true` in case Application instance supports requested OAuth grant flow
347   # during the authorization request to the server. This configuration +doesn't+
348   # set flows per application, it only allows to check if application supports
349   # specific grant flow.
350   #
351   # For example you can add an additional database column to `oauth_applications` table,
352   # say `t.array :grant_flows, default: []`, and store allowed grant flows that can
353   # be used with this application there. Then when authorization requested Doorkeeper
354   # will call this block to check if specific Application (passed with client_id and/or
355   # client_secret) is allowed to perform the request for the specific grant type
356   # (authorization, password, client_credentials, etc).
357   #
358   # Example of the block:
359   #
360   #   ->(flow, client) { client.grant_flows.include?(flow) }
361   #
362   # In case this option invocation result is `false`, Doorkeeper server returns
363   # :unauthorized_client error and stops the request.
364   #
365   # @param allow_grant_flow_for_client [Proc] Block or any object respond to #call
366   # @return [Boolean] `true` if allow or `false` if forbid the request
367   #
368   # allow_grant_flow_for_client do |grant_flow, client|
369   #   # `grant_flows` is an Array column with grant
370   #   # flows that application supports
371   #
372   #   client.grant_flows.include?(grant_flow)
373   # end
374
375   # If you need arbitrary Resource Owner-Client authorization you can enable this option
376   # and implement the check your need. Config option must respond to #call and return
377   # true in case resource owner authorized for the specific application or false in other
378   # cases.
379   #
380   # Be default all Resource Owners are authorized to any Client (application).
381   #
382   # authorize_resource_owner_for_client do |client, resource_owner|
383   #   resource_owner.admin? || client.owners_whitelist.include?(resource_owner)
384   # end
385
386   # Hook into the strategies' request & response life-cycle in case your
387   # application needs advanced customization or logging:
388   #
389   # before_successful_strategy_response do |request|
390   #   puts "BEFORE HOOK FIRED! #{request}"
391   # end
392   #
393   # after_successful_strategy_response do |request, response|
394   #   puts "AFTER HOOK FIRED! #{request}, #{response}"
395   # end
396
397   # Hook into Authorization flow in order to implement Single Sign Out
398   # or add any other functionality. Inside the block you have an access
399   # to `controller` (authorizations controller instance) and `context`
400   # (Doorkeeper::OAuth::Hooks::Context instance) which provides pre auth
401   # or auth objects with issued token based on hook type (before or after).
402   #
403   # before_successful_authorization do |controller, context|
404   #   Rails.logger.info(controller.request.params.inspect)
405   #
406   #   Rails.logger.info(context.pre_auth.inspect)
407   # end
408   #
409   # after_successful_authorization do |controller, context|
410   #   controller.session[:logout_urls] <<
411   #     Doorkeeper::Application
412   #       .find_by(controller.request.params.slice(:redirect_uri))
413   #       .logout_uri
414   #
415   #   Rails.logger.info(context.auth.inspect)
416   #   Rails.logger.info(context.issued_token)
417   # end
418
419   # Under some circumstances you might want to have applications auto-approved,
420   # so that the user skips the authorization step.
421   # For example if dealing with a trusted application.
422
423   skip_authorization do |_, client|
424     client.scopes.include?("skip_authorization")
425   end
426
427   # Configure custom constraints for the Token Introspection request.
428   # By default this configuration option allows to introspect a token by another
429   # token of the same application, OR to introspect the token that belongs to
430   # authorized client (from authenticated client) OR when token doesn't
431   # belong to any client (public token). Otherwise requester has no access to the
432   # introspection and it will return response as stated in the RFC.
433   #
434   # Block arguments:
435   #
436   # @param token [Doorkeeper::AccessToken]
437   #   token to be introspected
438   #
439   # @param authorized_client [Doorkeeper::Application]
440   #   authorized client (if request is authorized using Basic auth with
441   #   Client Credentials for example)
442   #
443   # @param authorized_token [Doorkeeper::AccessToken]
444   #   Bearer token used to authorize the request
445   #
446   # In case the block returns `nil` or `false` introspection responses with 401 status code
447   # when using authorized token to introspect, or you'll get 200 with { "active": false } body
448   # when using authorized client to introspect as stated in the
449   # RFC 7662 section 2.2. Introspection Response.
450   #
451   # Using with caution:
452   # Keep in mind that these three parameters pass to block can be nil as following case:
453   #  `authorized_client` is nil if and only if `authorized_token` is present, and vice versa.
454   #  `token` will be nil if and only if `authorized_token` is present.
455   # So remember to use `&` or check if it is present before calling method on
456   # them to make sure you doesn't get NoMethodError exception.
457   #
458   # You can define your custom check:
459   #
460   # allow_token_introspection do |token, authorized_client, authorized_token|
461   #   if authorized_token
462   #     # customize: require `introspection` scope
463   #     authorized_token.application == token&.application ||
464   #       authorized_token.scopes.include?("introspection")
465   #   elsif token.application
466   #     # `protected_resource` is a new database boolean column, for example
467   #     authorized_client == token.application || authorized_client.protected_resource?
468   #   else
469   #     # public token (when token.application is nil, token doesn't belong to any application)
470   #     true
471   #   end
472   # end
473   #
474   # Or you can completely disable any token introspection:
475   #
476   # allow_token_introspection false
477   #
478   # If you need to block the request at all, then configure your routes.rb or web-server
479   # like nginx to forbid the request.
480
481   # WWW-Authenticate Realm (default: "Doorkeeper").
482   #
483   # realm "Doorkeeper"
484 end