module Keycloak::Client

Constants

KEYCLOACK_CONTROLLER_DEFAULT

Attributes

auth_server_url[RW]
client_id[RW]
configuration[RW]
public_key[RW]
realm[RW]
secret[RW]

Public Class Methods

decoded_access_token(access_token = '') click to toggle source
# File lib/keycloak.rb, line 294
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_refresh_token(refresh_token = '') click to toggle source
# File lib/keycloak.rb, line 299
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
external_attributes() click to toggle source
# File lib/keycloak.rb, line 286
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 = '') click to toggle source
# File lib/keycloak.rb, line 271
def self.get_attribute(attributeName, access_token = '')
  verify_setup

  attr = decoded_access_token(access_token)[0]
  attr[attributeName]
end
get_token(user, password) click to toggle source
# File lib/keycloak.rb, line 40
def self.get_token(user, password)
  setup_module

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

  res = mount_request_token(payload)
  json = JSON.parse(res)
  Keycloak::Token.new(
    access_token: json["access_token"],
    expires_in: json["expires_in"],
    refresh_expires_in: json["refresh_expires_in"],
    refresh_token: json["refresh_token"],
    token_type: json["token_type"],
    not_before_policy: json["not-before-policy"],
    session_state: json["session_state"],
    scope: json["scope"]
  )
end
get_token_by_client_credentials(client_id = '', secret = '') click to toggle source
# File lib/keycloak.rb, line 123
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) click to toggle source
# File lib/keycloak.rb, line 63
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_exchange(issuer, issuer_token) click to toggle source
# File lib/keycloak.rb, line 75
def self.get_token_by_exchange(issuer, issuer_token)
  setup_module 
  
  payload = { 'client_id' => @client_id, 'client_secret' => @secret, 'audience' => @client_id, 'grant_type' => 'urn:ietf:params:oauth:grant-type:token-exchange', 'subject_token_type' => 'urn:ietf:params:oauth:token-type:access_token', 'subject_issuer' => issuer, 'subject_token' => issuer_token }
  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
    response.body 
  }
  end
   
    exec_request _request 
end
get_token_by_refresh_token(refresh_token = '') click to toggle source
# File lib/keycloak.rb, line 110
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 = '', client_id = '', secret = '') click to toggle source
# File lib/keycloak.rb, line 136
def self.get_token_introspection(token = '', client_id = '', secret = '')
  verify_setup

  token = self.token["access_token"] if token.empty?
  payload = { 'token' => token }

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

  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 = '') click to toggle source
# File lib/keycloak.rb, line 209
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
get_userinfo_issuer(access_token = '') click to toggle source
# File lib/keycloak.rb, line 95
def self.get_userinfo_issuer(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|
      response.body 
    } 
  end
  
  exec_request _request 
end
has_role?(user_role, access_token = '') click to toggle source
# File lib/keycloak.rb, line 238
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 = '') click to toggle source
# File lib/keycloak.rb, line 172
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
token() click to toggle source
# File lib/keycloak.rb, line 278
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') click to toggle source
# File lib/keycloak.rb, line 165
def self.url_login_redirect(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_account() click to toggle source
# File lib/keycloak.rb, line 232
def self.url_user_account
  verify_setup

  "#{@auth_server_url}/realms/#{@realm}/account"
end
user_signed_in?(access_token = '') click to toggle source
# File lib/keycloak.rb, line 257
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

Private Class Methods

decoded_id_token(idToken = '') click to toggle source
# File lib/keycloak.rb, line 381
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
exec_request(proc_request) click to toggle source
# File lib/keycloak.rb, line 338
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
get_installation() click to toggle source
# File lib/keycloak.rb, line 308
def self.get_installation
  if File.exists?(Keycloak.installation_file)
    installation = JSON File.read(Keycloak.installation_file)
    @realm = installation["realm"]
    @client_id = installation["resource"]
    @secret = installation["credentials"]["secret"]
    @public_key = installation["realm-public-key"]
    @auth_server_url = installation["auth-server-url"]
    openid_configuration
  else
    if Keycloak.realm.empty? || Keycloak.auth_server_url.empty?
      raise "#{Keycloak.installation_file} and relm settings not found."
    else
      @realm = Keycloak.realm
      @auth_server_url = Keycloak.auth_server_url
      openid_configuration
    end
  end
end
mount_request_token(payload) click to toggle source
# File lib/keycloak.rb, line 364
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_configuration() click to toggle source
# File lib/keycloak.rb, line 350
def self.openid_configuration
  RestClient.proxy = Keycloak.proxy unless Keycloak.proxy.empty?
  config_url = "#{@auth_server_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_module() click to toggle source
# File lib/keycloak.rb, line 332
def self.setup_module
  Keycloak.proxy ||= ''
  Keycloak.keycloak_controller ||= KEYCLOACK_CONTROLLER_DEFAULT
  get_installation
end
verify_setup() click to toggle source
# File lib/keycloak.rb, line 328
def self.verify_setup
  get_installation if @configuration.nil?
end