Class: Verikloak::Rails::ErrorRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/verikloak/rails/error_renderer.rb

Overview

Renders JSON errors for authentication/authorization failures.

When status is 401, adds a ‘WWW-Authenticate: Bearer` header including `error` and `error_description` fields when available.

Constant Summary collapse

DEFAULT_STATUS_MAP =
{
  'invalid_token' => 401,
  'unauthorized' => 401,
  'forbidden' => 403,
  'jwks_fetch_failed' => 503,
  'jwks_parse_failed' => 503,
  'discovery_metadata_fetch_failed' => 503,
  'discovery_metadata_invalid' => 503,
  # Additional infrastructure/configuration errors from core
  'invalid_discovery_url' => 503,
  'discovery_redirect_error' => 503
}.freeze

Instance Method Summary collapse

Instance Method Details

#render(controller, error) ⇒ void

This method returns an undefined value.

Render an error as JSON, adding ‘WWW-Authenticate` when appropriate.

Examples:

begin
  do_auth!
rescue Verikloak::Error => e
  Verikloak::Rails.config.error_renderer.render(self, e)
end

Parameters:

  • controller (#response, #render)

    a Rails controller instance

  • error (Exception)

    the error to render



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/verikloak/rails/error_renderer.rb', line 34

def render(controller, error)
  code, message = extract_code_message(error)
  status = status_for(error, code)
  headers = {}
  if status == 401
    hdr = +'Bearer'
    hdr << %( error="#{sanitize_quoted(code)}") if code
    hdr << %( error_description="#{sanitize_quoted(message)}") if message
    headers['WWW-Authenticate'] = hdr
  end
  headers.each { |k, v| controller.response.set_header(k, v) }
  controller.render json: { error: code || 'unauthorized', message: message }, status: status
end