Class: Keycloak::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/keycloak-api-rails/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



4
5
6
# File 'lib/keycloak-api-rails/middleware.rb', line 4

def initialize(app)
  @app = app
end

Instance Method Details

#authentication_failed(message) ⇒ Object



27
28
29
# File 'lib/keycloak-api-rails/middleware.rb', line 27

def authentication_failed(message)
  [401, {"Content-Type" => "application/json"}, [ { error: message }.to_json]]
end

#authentication_succeeded(env, decoded_token) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/keycloak-api-rails/middleware.rb', line 31

def authentication_succeeded(env, decoded_token)
  Helper.assign_current_user_id(env, decoded_token)
  Helper.assign_current_authorized_party(env, decoded_token)
  Helper.assign_current_user_email(env, decoded_token)
  Helper.assign_current_user_locale(env, decoded_token)
  Helper.assign_current_user_custom_attributes(env, decoded_token, config.custom_attributes)
  Helper.assign_realm_roles(env, decoded_token)
  Helper.assign_resource_roles(env, decoded_token)
  Helper.assign_keycloak_token(env, decoded_token)
  @app.call(env)
end

#call(env) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/keycloak-api-rails/middleware.rb', line 8

def call(env)
  method = env["REQUEST_METHOD"]
  path   = env["PATH_INFO"]
  uri    = env["REQUEST_URI"]

  if service.need_middleware_authentication?(method, path, env)
    logger.debug("Start authentication for #{method} : #{path}")
    token         = service.read_token(uri, env)
    decoded_token = service.decode_and_verify(token)
    authentication_succeeded(env, decoded_token)
  else
    logger.debug("Skip authentication for #{method} : #{path}")
    @app.call(env)
  end
rescue TokenError => e
  logger.debug("The error causing the Token to fail: #{e.original_error&.message || e.message}")
  authentication_failed(e.message)
end

#configObject



51
52
53
# File 'lib/keycloak-api-rails/middleware.rb', line 51

def config
  Keycloak.config
end

#loggerObject



47
48
49
# File 'lib/keycloak-api-rails/middleware.rb', line 47

def logger
  Keycloak.logger
end

#serviceObject



43
44
45
# File 'lib/keycloak-api-rails/middleware.rb', line 43

def service
  Keycloak.service
end