class Frodo::Middleware::Authentication
Faraday middleware that allows for on the fly authentication of requests. When a request fails (a status of 401 is returned), the middleware will attempt to either reauthenticate (username and password) or refresh the oauth access token (if a refresh token is present).
Public Instance Methods
authenticate!()
click to toggle source
Internal: Performs the authentication and returns the response body.
# File lib/frodo/middleware/authentication.rb, line 23 def authenticate! response = connection.post token_endpoint do |req| req.body = encode_www_form(params) end if response.status >= 500 raise Frodo::ServerError, error_message(response) elsif response.status != 200 raise Frodo::AuthenticationError, error_message(response) end @options[:oauth_token] = response.body['access_token'] @options[:refresh_token] = response.body['refresh_token'] @options[:authentication_callback]&.call(response.body) response.body end
call(env)
click to toggle source
Rescue from 401's, authenticate then raise the error again so the client can reissue the request.
# File lib/frodo/middleware/authentication.rb, line 15 def call(env) @app.call(env) rescue Frodo::UnauthorizedError authenticate! raise end
connection()
click to toggle source
Internal: Faraday connection to use when sending an authentication request.
# File lib/frodo/middleware/authentication.rb, line 47 def connection @connection ||= Faraday.new(faraday_options) do |builder| builder.use Faraday::Request::UrlEncoded builder.response :json if Frodo.log? builder.use Frodo::Middleware::Logger, Frodo.configuration.logger, @options end builder.adapter @options[:adapter] end end
encode_www_form(params)
click to toggle source
Featured detect form encoding. URI in 1.8 does not include encode_www_form
# File lib/frodo/middleware/authentication.rb, line 69 def encode_www_form(params) if URI.respond_to?(:encode_www_form) URI.encode_www_form(params) else params.map do |k, v| k = CGI.escape(k.to_s) v = CGI.escape(v.to_s) "#{k}=#{v}" end.join('&') end end
error_message(response)
click to toggle source
Internal: The parsed error response.
# File lib/frodo/middleware/authentication.rb, line 63 def error_message(response) "#{response.body['error']}: #{response.body['error_description']}" end
params()
click to toggle source
Internal: The params to post to the OAuth service.
# File lib/frodo/middleware/authentication.rb, line 42 def params raise NotImplementedError end
Private Instance Methods
faraday_options()
click to toggle source
# File lib/frodo/middleware/authentication.rb, line 83 def faraday_options { url: "https://#{@options[:host]}", proxy: @options[:proxy_uri], ssl: @options[:ssl] } end
token_endpoint()
click to toggle source
# File lib/frodo/middleware/authentication.rb, line 89 def token_endpoint "/#{@options[:tenant_id] || 'common'}/oauth2/token" end