class FaradayOauth2CcgMiddleware::ClientCredentialsGrant
Authorizes the request with the OAUTH2 Client Credentials Grant and injects the received token into the Authorization header
@example Configure OAUTH Client Credentials Grant middleware Faraday.new do |conn|
conn.request :oauth2_ccg, oauth_host: 'https://server.example.com', token_url: '/token', client_id: 's6BhdRkqt3', client_secret: '7Fjfp0ZBr1KtDRbnfVdmIw', cache_store: ::ActiveSupport::Cache.lookup_store(:redis_store, 'redis://127.0.0.1:6379') conn.adapter(:net_http) # NB: Last middleware must be the adapter
end
Constants
- AUTHORIZATION_HEADER
- BEARER_AUTHORIZATION
- CLIENT_CREDENTIALS_GRANT
Public Class Methods
new(app, options = nil)
click to toggle source
@param app [#call] @param options [Hash] @option options [String] :oauth_host ('') OAUTH2 server host @option options [String] :token_url ('') Token endpoint to request authorization @option options [String] :client_id ('') Client authentication id @option options [String] :client_secret ('') Client authentication password @option options [Class] :cache_store (nil) An ActiveSupport::Cache::Store instance for token caching
Calls superclass method
# File lib/faraday_oauth2_ccg_middleware.rb, line 66 def initialize(app, options = nil) super(app) @options = Options.from(options) end
Public Instance Methods
call(env)
click to toggle source
@param env [Faraday::Env]
# File lib/faraday_oauth2_ccg_middleware.rb, line 72 def call(env) env[:request_headers][AUTHORIZATION_HEADER] = "#{BEARER_AUTHORIZATION} #{token}" @app.call env end
Private Instance Methods
auth_conn()
click to toggle source
# File lib/faraday_oauth2_ccg_middleware.rb, line 105 def auth_conn Faraday.new(url: @options.oauth_host) end
cache_key()
click to toggle source
# File lib/faraday_oauth2_ccg_middleware.rb, line 109 def cache_key Digest::MD5.hexdigest("#{@options.oauth_host}#{@options.client_id}#{@options.client_secret}") end
oauth_response()
click to toggle source
# File lib/faraday_oauth2_ccg_middleware.rb, line 96 def oauth_response auth_conn.post( @options.token_url, grant_type: CLIENT_CREDENTIALS_GRANT, client_id: @options.client_id, client_secret: @options.client_secret ) end
token()
click to toggle source
# File lib/faraday_oauth2_ccg_middleware.rb, line 80 def token if @options.cache_store access_token = @options.cache_store.fetch(cache_key) return access_token if access_token.present? end token = JSON.parse(oauth_response.body) if @options.cache_store @options.cache_store.write(cache_key, token['access_token'], expires_in: token['expires_in']) end token['access_token'] end