class MAuth::Rack::RequestAuthenticator
middleware which will check that a request is authentically signed.
if the request is checked and is not authentic, 401 Unauthorized is returned and the app is not called.
options accepted (key may be string or symbol)
-
should_authenticate_check: a proc which should accept a rack env as an argument, and return true if the request should be authenticated; false if not. if the result from this is false, the request is passed to the app with no authentication performed.
Public Instance Methods
# File lib/mauth/rack.rb, line 17 def call(env) mauth_request = MAuth::Rack::Request.new(env) env['mauth.protocol_version'] = mauth_request.protocol_version return @app.call(env) unless should_authenticate?(env) if mauth_client.v2_only_authenticate? && mauth_request.protocol_version == 1 return response_for_missing_v2(env) end begin if mauth_client.authentic?(mauth_request) @app.call(env.merge!( 'mauth.app_uuid' => mauth_request.signature_app_uuid, 'mauth.authentic' => true )) else response_for_inauthentic_request(env) end rescue MAuth::UnableToAuthenticateError response_for_unable_to_authenticate(env) end end
discards the body if REQUEST_METHOD is HEAD. sets the Content-Length.
# File lib/mauth/rack.rb, line 42 def handle_head(env) status, headers, body = *yield headers["Content-Length"] = body.map(&:bytesize).inject(0, &:+).to_s [status, headers, env['REQUEST_METHOD'].casecmp('head').zero? ? [] : body] end
response when the request is inauthentic. responds with status 401 Unauthorized and a message.
# File lib/mauth/rack.rb, line 55 def response_for_inauthentic_request(env) handle_head(env) do body = { 'errors' => { 'mauth' => ['Unauthorized'] } } [401, { 'Content-Type' => 'application/json' }, [JSON.pretty_generate(body)]] end end
response when the requests includes V1 headers but does not include V2 headers and the V2_ONLY_AUTHENTICATE flag is set.
# File lib/mauth/rack.rb, line 74 def response_for_missing_v2(env) handle_head(env) do body = { 'type' => 'errors:mauth:missing_v2', 'title' => 'This service requires mAuth v2 mcc-authentication header. Upgrade your mAuth library and configure it properly.' } [401, { 'Content-Type' => 'application/json' }, [JSON.pretty_generate(body)]] end end
response when the authenticity of the request cannot be determined, due to a problem communicating with the MAuth
service. responds with a status of 500 and a message.
# File lib/mauth/rack.rb, line 65 def response_for_unable_to_authenticate(env) handle_head(env) do body = { 'errors' => { 'mauth' => ['Could not determine request authenticity'] } } [500, { 'Content-Type' => 'application/json' }, [JSON.pretty_generate(body)]] end end
whether the request needs to be authenticated
# File lib/mauth/rack.rb, line 49 def should_authenticate?(env) @config['should_authenticate_check'] ? @config['should_authenticate_check'].call(env) : true end