Class: KeycloakRack::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/keycloak_rack/middleware.rb

Overview

Rack middleware that calls Authenticate to process a keycloak token.

Upon successful processing, it populates the following values into the rack environment for consumption later down the stack:

  • keycloak:session: An instance of Session that serves as the primary interface
  • keycloak:authorize_realm: An instance of AuthorizeRealm for authorizing realm-level roles
  • keycloak:authorize_resource: An instance of AuthorizeResource for authorizing resource-level roles

Instance Method Summary collapse

Constructor Details

#initialize(app, **options) ⇒ Middleware

Returns a new instance of Middleware.

Parameters:

  • app (#call)

    the next component in the rack middleware stack


18
19
20
21
22
# File 'lib/keycloak_rack/middleware.rb', line 18

def initialize(app, **options)
  super(**options)

  @app = app
end

Instance Method Details

#call(env) ⇒ Object

Process the rack environment and inject the gem's interfaces into it.

If the authentication is a monadic failure, and halt_on_auth_failure is true, then it will short-circuit with #authentication_failed.

Parameters:

  • env (Hash)

    the rack environment

Returns:

  • (Object)

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/keycloak_rack/middleware.rb', line 31

def call(env)
  result = authenticate.call(env)

  return authentication_failed(env, result) if halt?(result)

  session_opts = { skipped: false, auth_result: result }

  case result
  in Success[:authenticated, decoded_token]
    session_opts[:token] = decoded_token
  in Success[:skipped]
    session_opts[:skipped] = true
  else
    # nothing to do
  end

  env["keycloak:session"] = session = KeycloakRack::Session.new(**session_opts)
  env["keycloak:authorize_realm"] = session.authorize_realm
  env["keycloak:authorize_resource"] = session.authorize_resource

  @app.call(env)
end