Module: Keycloak::Client

Defined in:
lib/keycloak.rb

Constant Summary collapse

KEYCLOAK_JSON_FILE =
'keycloak.json'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.auth_server_urlObject (readonly)

Returns the value of attribute auth_server_url.



24
25
26
# File 'lib/keycloak.rb', line 24

def auth_server_url
  @auth_server_url
end

.client_idObject (readonly)

Returns the value of attribute client_id.



24
25
26
# File 'lib/keycloak.rb', line 24

def client_id
  @client_id
end

.configurationObject (readonly)

Returns the value of attribute configuration.



24
25
26
# File 'lib/keycloak.rb', line 24

def configuration
  @configuration
end

.public_keyObject (readonly)

Returns the value of attribute public_key.



24
25
26
# File 'lib/keycloak.rb', line 24

def public_key
  @public_key
end

.realmObject (readonly)

Returns the value of attribute realm.



24
25
26
# File 'lib/keycloak.rb', line 24

def realm
  @realm
end

.secretObject (readonly)

Returns the value of attribute secret.



24
25
26
# File 'lib/keycloak.rb', line 24

def secret
  @secret
end

.urlObject (readonly)

Returns the value of attribute url.



24
25
26
# File 'lib/keycloak.rb', line 24

def url
  @url
end

Class Method Details

.decoded_access_token(access_token = '') ⇒ Object



309
310
311
312
# File 'lib/keycloak.rb', line 309

def self.decoded_access_token(access_token = '')
  access_token = self.token["access_token"] if access_token.empty?
  JWT.decode access_token, @public_key, false, { :algorithm => 'RS256' }
end

.decoded_id_token(idToken = '') ⇒ Object



319
320
321
322
323
324
325
# File 'lib/keycloak.rb', line 319

def self.decoded_id_token(idToken = '')
  tk = self.token
  idToken = tk["id_token"] if idToken.empty?
  if idToken
    @decoded_id_token = JWT.decode idToken, @public_key, false, { :algorithm => 'RS256' }
  end
end

.decoded_refresh_token(refresh_token = '') ⇒ Object



314
315
316
317
# File 'lib/keycloak.rb', line 314

def self.decoded_refresh_token(refresh_token = '')
  refresh_token = self.token["access_token"] if refresh_token.empty?
  JWT.decode refresh_token, @public_key, false, { :algorithm => 'RS256' }
end

.exec_request(proc_request) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
# File 'lib/keycloak.rb', line 266

def self.exec_request(proc_request)
  if Keycloak.explode_exception
    proc_request.call
  else
    begin
      proc_request.call
    rescue RestClient::ExceptionWithResponse => err
      err.response
    end
  end
end

.external_attributesObject



229
230
231
232
233
234
235
# File 'lib/keycloak.rb', line 229

def self.external_attributes
  if !Keycloak.proc_external_attributes.nil?
    Keycloak.proc_external_attributes.call
  else
    raise Keycloak::ProcExternalAttributesNotDefined
  end
end

.get_attribute(attributeName, access_token = '') ⇒ Object



214
215
216
217
218
219
# File 'lib/keycloak.rb', line 214

def self.get_attribute(attributeName, access_token = '')
  verify_setup

  attr = decoded_access_token(access_token)[0]
  attr[attributeName]
end

.get_installationObject



241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/keycloak.rb', line 241

def self.get_installation
  if File.exists?(KEYCLOAK_JSON_FILE)
    installation = JSON File.read(KEYCLOAK_JSON_FILE)
    @realm = installation["realm"]
    @url = installation["auth-server-url"]
    @client_id = installation["resource"]
    @secret = installation["credentials"]["secret"]
    @public_key = installation["realm-public-key"]
    @auth_server_url = installation["auth-server-url"]
    openid_configuration
  else
    raise "#{KEYCLOAK_JSON_FILE} not found."
  end
end

.get_token(user, password) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/keycloak.rb', line 30

def self.get_token(user, password)
  setup_module

  payload = { 'client_id' => @client_id,
              'client_secret' => @secret,
              'username' => user,
              'password' => password,
              'grant_type' => 'password' }

  mount_request_token(payload)
end

.get_token_by_client_credentials(client_id = '', secret = '') ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/keycloak.rb', line 67

def self.get_token_by_client_credentials(client_id = '', secret = '')
  setup_module

  client_id = @client_id if client_id.empty?
  secret = @secret if secret.empty?

  payload = { 'client_id' => client_id,
              'client_secret' => secret,
              'grant_type' => 'client_credentials' }

  mount_request_token(payload)
end

.get_token_by_code(code, redirect_uri) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/keycloak.rb', line 42

def self.get_token_by_code(code, redirect_uri)
  verify_setup

  payload = { 'client_id' => @client_id,
              'client_secret' => @secret,
              'code' => code,
              'grant_type' => 'authorization_code',
              'redirect_uri' => redirect_uri }

  mount_request_token(payload)
end

.get_token_by_refresh_token(refresh_token = '') ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/keycloak.rb', line 54

def self.get_token_by_refresh_token(refresh_token = '')
  verify_setup

  refresh_token = self.token['refresh_token'] if refresh_token.empty?

  payload = { 'client_id' => @client_id,
              'client_secret' => @secret,
              'refresh_token' => refresh_token,
              'grant_type' => 'refresh_token' }

  mount_request_token(payload)
end

.get_token_introspection(token = '') ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/keycloak.rb', line 80

def self.get_token_introspection(token = '')
  verify_setup

  token = self.token["access_token"] if token.empty?

  payload = { 'token' => token }

  authorization = Base64.strict_encode64("#{@client_id}:#{@secret}")
  authorization = "Basic #{authorization}"

  header = {'Content-Type' => 'application/x-www-form-urlencoded',
            'authorization' => authorization}

  _request = -> do
    RestClient.post(@configuration['token_introspection_endpoint'], payload, header){|response, request, result|
      case response.code
      when 200..399
        response.body

      else
        response.return!
      end
    }
  end

  exec_request _request
end

.get_userinfo(access_token = '') ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/keycloak.rb', line 152

def self.get_userinfo(access_token = '')
  verify_setup

  access_token = self.token["access_token"] if access_token.empty?

  payload = { 'access_token' => access_token }

  header = { 'Content-Type' => 'application/x-www-form-urlencoded' }

  _request = -> do
    RestClient.post(@configuration['userinfo_endpoint'], payload, header){ |response, request, result|
      case response.code
      when 200
        response.body
      else
        response.return!
      end
    }
  end

  exec_request _request
end

.has_role?(user_role, access_token = '') ⇒ Boolean

Returns:

  • (Boolean)


181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/keycloak.rb', line 181

def self.has_role?(user_role, access_token = '')
  verify_setup

  if user_signed_in?(access_token)
    dt = decoded_access_token(access_token)[0]
    dt = dt["resource_access"][@client_id]
    if dt != nil
      dt["roles"].each do |role|
        return true if role.to_s == user_role.to_s
      end
      false
    else
      false
    end
  else
    false
  end
end

.logout(redirect_uri = '', refresh_token = '') ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/keycloak.rb', line 115

def self.logout(redirect_uri = '', refresh_token = '')
  verify_setup

  if self.token || !refresh_token.empty?

    refresh_token = self.token['refresh_token'] if refresh_token.empty?

    payload = { 'client_id' => @client_id,
                'client_secret' => @secret,
                'refresh_token' => refresh_token
          }

    header = {'Content-Type' => 'application/x-www-form-urlencoded'}

    if redirect_uri.empty?
      final_url = @configuration['end_session_endpoint']
    else
      final_url = "#{@configuration['end_session_endpoint']}?#{URI.encode_www_form({ redirect_uri: redirect_uri })}"
    end

    _request = -> do
      RestClient.post(final_url, payload, header){ |response, request, result|
        case response.code
        when 200..399
          true
        else
          response.return!
        end
      }
    end

    exec_request _request
  else
    true
  end
end

.mount_request_token(payload) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/keycloak.rb', line 292

def self.mount_request_token(payload)
  header = {'Content-Type' => 'application/x-www-form-urlencoded'}

  _request = -> do
    RestClient.post(@configuration['token_endpoint'], payload, header){|response, request, result|
      case response.code
      when 200
        response.body
      else
        response.return!
      end
    }
  end

  exec_request _request
end

.openid_configurationObject



278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/keycloak.rb', line 278

def self.openid_configuration
  RestClient.proxy = Keycloak.proxy unless Keycloak.proxy.empty?
  config_url = "#{@url}/realms/#{@realm}/.well-known/openid-configuration"
  _request = -> do
    RestClient.get config_url
  end
  response = exec_request _request
  if response.code == 200
    @configuration = JSON response.body
  else
    response.return!
  end
end

.setup_moduleObject



260
261
262
263
264
# File 'lib/keycloak.rb', line 260

def self.setup_module
  Keycloak.proxy ||= ''
  Keycloak.keycloak_controller ||= KEYCLOACK_CONTROLLER_DEFAULT
  get_installation
end

.tokenObject



221
222
223
224
225
226
227
# File 'lib/keycloak.rb', line 221

def self.token
  if !Keycloak.proc_cookie_token.nil?
    JSON Keycloak.proc_cookie_token.call
  else
    raise Keycloak::ProcCookieTokenNotDefined
  end
end

.url_login_redirect(redirect_uri, response_type = 'code') ⇒ Object



108
109
110
111
112
113
# File 'lib/keycloak.rb', line 108

def self.(redirect_uri, response_type = 'code')
  verify_setup

  p = URI.encode_www_form({ response_type: response_type, client_id: @client_id, redirect_uri: redirect_uri })
  "#{@configuration['authorization_endpoint']}?#{p}"
end

.url_user_accountObject



175
176
177
178
179
# File 'lib/keycloak.rb', line 175

def self.
  verify_setup

  "#{@url}/realms/#{@realm}/account"
end

.user_signed_in?(access_token = '') ⇒ Boolean

Returns:

  • (Boolean)


200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/keycloak.rb', line 200

def self.user_signed_in?(access_token = '')
  verify_setup

  begin
    JSON(get_token_introspection(access_token))['active'] === true
  rescue => e
    if e.class < Keycloak::KeycloakException
      raise
    else
      false
    end
  end
end

.verify_setupObject



256
257
258
# File 'lib/keycloak.rb', line 256

def self.verify_setup
  get_installation if @configuration.nil?
end