You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by is...@apache.org on 2020/08/14 13:48:50 UTC

[airavata-php-gateway] branch custos-integration updated: Fix getAccessTokenAPI

This is an automated email from the ASF dual-hosted git repository.

isjarana pushed a commit to branch custos-integration
in repository https://gitbox.apache.org/repos/asf/airavata-php-gateway.git


The following commit(s) were added to refs/heads/custos-integration by this push:
     new 4f3e572  Fix getAccessTokenAPI
4f3e572 is described below

commit 4f3e57273633cf02dd8be9812923c17707854259
Author: Isuru Ranawaka <ir...@gmail.com>
AuthorDate: Fri Aug 14 09:48:26 2020 -0400

    Fix getAccessTokenAPI
---
 .../Keycloak/API/BaseKeycloakAPIEndpoint.php       |  8 ++-
 app/libraries/Keycloak/API/RoleMapper.php          | 56 +++++++++++------
 app/libraries/Keycloak/API/Roles.php               |  9 +--
 app/libraries/Keycloak/API/Users.php               |  6 +-
 app/libraries/Keycloak/Keycloak.php                | 70 +++++++---------------
 app/libraries/Keycloak/KeycloakUtil.php            | 36 ++++++++++-
 6 files changed, 106 insertions(+), 79 deletions(-)

diff --git a/app/libraries/Keycloak/API/BaseKeycloakAPIEndpoint.php b/app/libraries/Keycloak/API/BaseKeycloakAPIEndpoint.php
index de9a34b..62dc56b 100644
--- a/app/libraries/Keycloak/API/BaseKeycloakAPIEndpoint.php
+++ b/app/libraries/Keycloak/API/BaseKeycloakAPIEndpoint.php
@@ -16,8 +16,9 @@ class BaseKeycloakAPIEndpoint {
     protected  $client_id;
     protected  $client_secret;
     protected $openid_discovery_endpoint_url;
+    protected  $custos_credential_uri;
 
-    function __construct($openid_discovery_endpoint_url, $base_endpoint_url, $admin_username, $admin_password, $verify_peer, $cafile_path, $client_id, $client_secret) {
+    function __construct($openid_discovery_endpoint_url, $base_endpoint_url, $admin_username, $admin_password, $verify_peer, $cafile_path, $client_id, $client_secret, $custos_credential_uri) {
         $this->base_endpoint_url = $base_endpoint_url;
         $this->admin_username = $admin_username;
         $this->admin_password = $admin_password;
@@ -26,10 +27,11 @@ class BaseKeycloakAPIEndpoint {
         $this->client_id = $client_id;
         $this->client_secret = $client_secret;
         $this->openid_discovery_endpoint_url = $openid_discovery_endpoint_url;
+        $this->custos_credential_uri = $custos_credential_uri;
     }
 
-    protected function getAPIAccessToken($realm) {
+    protected function getAPIAccessToken() {
 
-        return KeycloakUtil::getAPIAccessToken($this->openid_discovery_endpoint_url, $realm, $this->admin_username, $this->admin_password, $this->verify_peer, $this->cafile_path, $this->client_id, $this->client_secret);
+        return KeycloakUtil::getAPIAccessToken($this->openid_discovery_endpoint_url, $this->custos_credential_uri, $this->admin_username, $this->admin_password, $this->verify_peer, $this->cafile_path, $this->client_id, $this->client_secret);
     }
 }
diff --git a/app/libraries/Keycloak/API/RoleMapper.php b/app/libraries/Keycloak/API/RoleMapper.php
index 041d76b..2436f47 100644
--- a/app/libraries/Keycloak/API/RoleMapper.php
+++ b/app/libraries/Keycloak/API/RoleMapper.php
@@ -56,9 +56,8 @@ class RoleMapper extends BaseKeycloakAPIEndpoint {
     public function addRealmRoleMappingsToUser($realm, $user_id, $role_representations) {
 
         // get access token for admin API
-        $access_token = $this->getAPIAccessToken($realm);
-        $url = $this->base_endpoint_url . '/admin/realms/' . rawurlencode($realm) . '/users/' . rawurlencode($user_id) . '/role-mappings/realm';
-        // Log::debug("addRealmRoleMappingsToUser", array($url, $role_representations));
+        $access_token = $this->getAPIAccessToken();
+        $url = $this->base_endpoint_url . 'user-management/v1.0.0/users/roles';
         $r = curl_init($url);
         curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($r, CURLOPT_ENCODING, 1);
@@ -68,19 +67,33 @@ class RoleMapper extends BaseKeycloakAPIEndpoint {
         }
 
         curl_setopt($r, CURLOPT_POST, true);
-        $data = json_encode($role_representations);
-        // Log::debug("addRealmRoleMappingsToUser data=$data");
+
+        $roles = [];
+        foreach ($role_representations as $role) {
+                    $roles[] = $role->name;
+        }
+
+        $usernames = [];
+        $usernames[] = $user_id;
+        $client_level = false;
+
+        $json =   array("roles"=> $roles, "usernames"=> $usernames, "client_level" => $client_level);
+
+
+        $data = json_encode($json);
+         Log::debug("addRealmRoleMappingsToUser data=$data");
         curl_setopt($r, CURLOPT_HTTPHEADER, array(
-            "Authorization: Bearer " . $access_token,
+            "Authorization: Bearer " .$access_token,
             'Content-Type: application/json',
             'Content-Length: ' . strlen($data))
         );
         curl_setopt($r, CURLOPT_POSTFIELDS, $data);
 
         $response = curl_exec($r);
-        $info = curl_getinfo($r);
-        if ($info['http_code'] != 200 && $info['http_code'] != 204) {
-            throw new Exception("Failed to add realm role mapping to user");
+
+        if ($response == false || ! ($response->status)) {
+            Log::error("Failed to add realm role mappings for user");
+            die("curl_exec() failed. Error: " . curl_error($r));
         }
         return;
     }
@@ -92,8 +105,8 @@ class RoleMapper extends BaseKeycloakAPIEndpoint {
     public function deleteRealmRoleMappingsToUser($realm, $user_id, $role_representations) {
 
         // get access token for admin API
-        $access_token = $this->getAPIAccessToken($realm);
-        $url = $this->base_endpoint_url . '/admin/realms/' . rawurlencode($realm) . '/users/' . rawurlencode($user_id) . '/role-mappings/realm';
+        $access_token = $this->getAPIAccessToken();
+        $url = $this->base_endpoint_url . 'user-management/v1.0.0/user/roles';
         // Log::debug("deleteRealmRoleMappingsToUser", array($url, $role_representations));
         $r = curl_init($url);
         curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
@@ -105,19 +118,28 @@ class RoleMapper extends BaseKeycloakAPIEndpoint {
 
         curl_setopt($r, CURLOPT_CUSTOMREQUEST, "DELETE");
         curl_setopt($r, CURLOPT_POST, true);
-        $data = json_encode($role_representations);
-        // Log::debug("deleteRealmRoleMappingsToUser data=$data");
+
+        $roles = [];
+        foreach ($role_representations as $role) {
+            $roles[] = $role->name;
+        }
+
+        $json =   array("roles"=> $roles, "username"=> $user_id);
+
+        $data = json_encode($json);
+         Log::debug("deleteRealmRoleMappingsToUser data=$data");
         curl_setopt($r, CURLOPT_HTTPHEADER, array(
-            "Authorization: Bearer " . $access_token,
+            "Authorization: Bearer " .$access_token,
             'Content-Type: application/json',
             'Content-Length: ' . strlen($data))
         );
         curl_setopt($r, CURLOPT_POSTFIELDS, $data);
 
         $response = curl_exec($r);
-        $info = curl_getinfo($r);
-        if ($info['http_code'] != 200 && $info['http_code'] != 204) {
-            throw new Exception("Failed to delete realm role mapping to user");
+
+        if ($response == false || ! ($response->status)) {
+            Log::error("Failed to add realm role mappings for user");
+            die("curl_exec() failed. Error: " . curl_error($r));
         }
         return;
     }
diff --git a/app/libraries/Keycloak/API/Roles.php b/app/libraries/Keycloak/API/Roles.php
index 1972e74..f6e28e4 100644
--- a/app/libraries/Keycloak/API/Roles.php
+++ b/app/libraries/Keycloak/API/Roles.php
@@ -17,8 +17,9 @@ class Roles extends BaseKeycloakAPIEndpoint {
     public function getRoles($realm){
 
         // get access token for admin API
-        $access_token = $this->getAPIAccessToken($realm);
-        $r = curl_init($this->base_endpoint_url . '/admin/realms/' . rawurlencode($realm) . '/roles');
+        $url = $this->base_endpoint_url . '/tenant-management/v1.0.0/roles';
+        $url = $url;
+        $r = curl_init($url);
         curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($r, CURLOPT_ENCODING, 1);
         curl_setopt($r, CURLOPT_SSL_VERIFYPEER, $this->verify_peer);
@@ -26,7 +27,7 @@ class Roles extends BaseKeycloakAPIEndpoint {
             curl_setopt($r, CURLOPT_CAINFO, $this->cafile_path);
         }
         curl_setopt($r, CURLOPT_HTTPHEADER, array(
-            "Authorization: Bearer " . $access_token
+            "Authorization: Basic " . base64_encode($this->client_id . ":" . $this->client_secret),
         ));
 
         $response = curl_exec($r);
@@ -35,6 +36,6 @@ class Roles extends BaseKeycloakAPIEndpoint {
         }
         $result = json_decode($response);
         // Log::debug("getRealmRoleMappingsForUser result", array($result));
-        return $result;
+        return $result->roles;
     }
 }
diff --git a/app/libraries/Keycloak/API/Users.php b/app/libraries/Keycloak/API/Users.php
index a5b6eb7..cc5fbee 100644
--- a/app/libraries/Keycloak/API/Users.php
+++ b/app/libraries/Keycloak/API/Users.php
@@ -47,7 +47,7 @@ class Users extends BaseKeycloakAPIEndpoint
         }
         $result = json_decode($response);
         // Log::debug("getUsers result", array($result));
-        return $result;
+        return $result->users;
     }
 
     public function getUserByUsername($realm, $username)
@@ -76,7 +76,7 @@ class Users extends BaseKeycloakAPIEndpoint
 
         // get access token for admin API
         $url = $this->base_endpoint_url . '/user-management/v1.0.0/users';
-        $params = "?client_id=" . urlencode($this->client_id) . "&offset=" . urlencode(0) . "&limit=" . urlencode(100) . "&keyword=" . urlencode($keyword);
+        $params = "?client_id=" . urlencode($this->client_id) . "&offset=" . urlencode(0) . "&limit=" . urlencode(100) . "&user.id=" . urlencode($keyword);
         // Log::debug("getUsers url", array($url));
         $url = $url . $params;
         $r = curl_init($url);
@@ -96,7 +96,7 @@ class Users extends BaseKeycloakAPIEndpoint
         }
         $result = json_decode($response);
         // Log::debug("getUsers result", array($result));
-        return $result;
+        return $result->users;
     }
 
     /**
diff --git a/app/libraries/Keycloak/Keycloak.php b/app/libraries/Keycloak/Keycloak.php
index cc1765f..c1d3e6a 100644
--- a/app/libraries/Keycloak/Keycloak.php
+++ b/app/libraries/Keycloak/Keycloak.php
@@ -52,9 +52,9 @@ class Keycloak
         $this->gateway_id = $gateway_id;
         $this->custos_credentials_uri = $custos_credentials_uri;
 
-        $this->role_mapper = new RoleMapper($openid_connect_discovery_url, $base_endpoint_url, $admin_username, $admin_password, $verify_peer, $this->cafile_path, $this->client_id, $this->client_secret);
-        $this->roles = new Roles($openid_connect_discovery_url, $base_endpoint_url, $admin_username, $admin_password, $verify_peer, $this->cafile_path, $this->client_id, $this->client_secret);
-        $this->users = new Users($openid_connect_discovery_url, $base_endpoint_url, $admin_username, $admin_password, $verify_peer, $this->cafile_path, $this->client_id, $this->client_secret);
+        $this->role_mapper = new RoleMapper($openid_connect_discovery_url, $base_endpoint_url, $admin_username, $admin_password, $verify_peer, $this->cafile_path, $this->client_id, $this->client_secret, $this->custos_credentials_uri);
+        $this->roles = new Roles($openid_connect_discovery_url, $base_endpoint_url, $admin_username, $admin_password, $verify_peer, $this->cafile_path, $this->client_id, $this->client_secret, $this->custos_credentials_uri);
+        $this->users = new Users($openid_connect_discovery_url, $base_endpoint_url, $admin_username, $admin_password, $verify_peer, $this->cafile_path, $this->client_id, $this->client_secret, $this->custos_credentials_uri);
     }
 
     /**
@@ -83,7 +83,7 @@ class Keycloak
             curl_setopt($r, CURLOPT_CAINFO, $this->cafile_path);
         }
 
-        $auth_credentials = $this->getAuthCredentials();
+        $auth_credentials = KeycloakUtil::getAuthCredentials($this->custos_credentials_uri, $this->client_id, $this->client_secret);
 
         $iam_secret = $auth_credentials->iam_client_secret;
 
@@ -147,7 +147,8 @@ class Keycloak
             curl_setopt($r, CURLOPT_CAINFO, $this->cafile_path);
         }
 
-        $auth_credentials = $this->getAuthCredentials();
+        $auth_credentials = KeycloakUtil::getAuthCredentials($this->custos_credentials_uri, $this->client_id, $this->client_secret);
+
 
         $iam_secret = $auth_credentials->iam_client_secret;
 
@@ -212,7 +213,7 @@ class Keycloak
         $role_mappings = $this->role_mapper->getRealmRoleMappingsForUser($username);
         $roles = [];
         foreach ($role_mappings as $role_mapping) {
-            $roles[] = $role_mapping->name;
+            $roles[] = $role_mapping;
         }
         $roles = CommonUtilities::filterAiravataRoles($roles);
         return array('username' => $username, 'firstname' => $firstname, 'lastname' => $lastname, 'email' => $email, 'roles' => $roles);
@@ -239,7 +240,8 @@ class Keycloak
             curl_setopt($r, CURLOPT_CAINFO, $this->cafile_path);
         }
 
-        $auth_credentials = $this->getAuthCredentials();
+        $auth_credentials = KeycloakUtil::getAuthCredentials($this->custos_credentials_uri, $this->client_id, $this->client_secret);
+
 
         $iam_secret = $auth_credentials->iam_client_secret;
 
@@ -290,7 +292,7 @@ class Keycloak
         $usernames = [];
         foreach ($users as $user) {
             Log::debug("user", array($user));
-            array_push($usernames, (object)["firstName" => $user->firstName, "lastName" => $user->lastName, "email" => $user->email, "userEnabled" => $user->enabled, "userName" => $user->username]);
+            array_push($usernames, (object)["firstName" => $user->first_name, "lastName" => $user->last_name, "email" => $user->email, "userEnabled" => ($user->state === "ACTIVE"), "userName" => $user->username]);
         }
         return $usernames;
     }
@@ -308,7 +310,7 @@ class Keycloak
         $users = $this->users->searchUsers($this->realm, $phrase);
         $usernames = [];
         foreach ($users as $user) {
-            array_push($usernames, (object)["firstName" => $user->firstName, "lastName" => $user->lastName, "email" => $user->email, "userEnabled" => $user->enabled, "userName" => $user->username]);
+            array_push($usernames, (object)["firstName" => $user->first_name, "lastName" => $user->last_name, "email" => $user->email, "userEnabled" => ($user->state === "ACTIVE"), "userName" => $user->username]);
         }
         return $usernames;
     }
@@ -345,12 +347,11 @@ class Keycloak
         try {
             Log::info("Calling getUserRoles");
             // get userid from username
-            $user_id = $this->getUserId($username);
             // Get the user's realm roles, then convert to an array of just names
-            $roles = $this->role_mapper->getRealmRoleMappingsForUser($user_id);
+            $roles = $this->role_mapper->getRealmRoleMappingsForUser($username);
             $role_names = [];
             foreach ($roles as $role) {
-                $role_names[] = $role->name;
+                $role_names[] = $role;
             }
             return CommonUtilities::filterAiravataRoles($role_names);
         } catch (Exception $ex) {
@@ -372,7 +373,6 @@ class Keycloak
         try {
             Log::info("Calling updateUserRoles");
             // get userid from username
-            $user_id = $this->getUserId($username);
             // Get all of the roles into an array keyed by role name
             $all_roles = $this->roles->getRoles($this->realm);
             $roles_by_name = [];
@@ -385,7 +385,7 @@ class Keycloak
                 if (!is_array($roles["deleted"]))
                     $roles["deleted"] = array($roles["deleted"]);
                 foreach ($roles["deleted"] as $role) {
-                    $this->role_mapper->deleteRealmRoleMappingsToUser($this->realm, $user_id, array($roles_by_name[$role]));
+                    $this->role_mapper->deleteRealmRoleMappingsToUser($this->realm, $username, array($roles_by_name[$role]));
                 }
             }
 
@@ -394,7 +394,7 @@ class Keycloak
                 if (!is_array($roles["new"]))
                     $roles["new"] = array($roles["new"]);
                 foreach ($roles["new"] as $role) {
-                    $this->role_mapper->addRealmRoleMappingsToUser($this->realm, $user_id, array($roles_by_name[$role]));
+                    $this->role_mapper->addRealmRoleMappingsToUser($this->realm, $username, array($roles_by_name[$role]));
                 }
             }
         } catch (Exception $ex) {
@@ -413,9 +413,9 @@ class Keycloak
         if ($user != null) {
             $result = [];
             $result["email"] = $user->email;
-            $result["firstname"] = $user->firstName;
-            $result["lastname"] = $user->lastName;
-            $result["userEnabled"] = $user->enabled;
+            $result["firstname"] = $user->first_name;
+            $result["lastname"] = $user->last_name;
+            $result["userEnabled"] = ($user->state === "ACTIVE");
             return $result;
         } else {
             return [];
@@ -461,7 +461,9 @@ class Keycloak
     public function getAdminAuthzToken()
     {
         Log::info("Calling getAdminAuthzToken");
-        $access_token = KeycloakUtil::getAPIAccessToken($this->openid_connect_discovery_url, $this->realm, $this->admin_username, $this->admin_password, $this->verify_peer, $this->cafile_path);
+        $access_token = KeycloakUtil::getAPIAccessToken($this->openid_connect_discovery_url, $this->custos_credentials_uri,
+            $this->admin_username, $this->admin_password, $this->verify_peer, $this->cafile_path,
+            $this->client_id, $this->client_secret);
         $authzToken = new \Airavata\Model\Security\AuthzToken();
         $authzToken->accessToken = $access_token;
         $authzToken->claimsMap['gatewayID'] = $this->gateway_id;
@@ -484,35 +486,5 @@ class Keycloak
     }
 
 
-    private function getAuthCredentials()
-    {
-
-        $post_files = "?client_id=" . urlencode($this->client_id);
-        $url = $this->custos_credentials_uri . $post_files;
-
-        // TODO: cache the result of the request
-        $r = curl_init($url);
-
-        curl_setopt($r, CURLOPT_HTTPHEADER, array(
-            "Authorization: Basic " . base64_encode($this->client_id . ":" . $this->client_secret),
-        ));
-
-
-        curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
-        // Decode compressed responses.
-        curl_setopt($r, CURLOPT_ENCODING, 1);
-
-        $result = curl_exec($r);
-        if ($result == false) {
-            die("curl_exec() failed. Error: " . curl_error($r));
-        }
-
-        $json = json_decode($result);
-
-        // Log::debug("openid connect discovery configuration", array($json));
-        return $json;
-    }
-
-
 }
 
diff --git a/app/libraries/Keycloak/KeycloakUtil.php b/app/libraries/Keycloak/KeycloakUtil.php
index 185e7eb..361db98 100644
--- a/app/libraries/Keycloak/KeycloakUtil.php
+++ b/app/libraries/Keycloak/KeycloakUtil.php
@@ -7,10 +7,10 @@ use Log;
 class KeycloakUtil
 {
 
-    public static function getAPIAccessToken($openid_connect_discovery_url, $realm, $admin_username, $admin_password, $verify_peer, $cafile_path, $client_id, $client_sec)
+    public static function getAPIAccessToken($openid_connect_discovery_url, $custos_credentials_uri, $admin_username, $admin_password, $verify_peer, $cafile_path, $client_id, $client_sec)
     {
 
-        $config = KeycloakUtil::getOpenIDConnectDiscoveryConfiguration($openid_connect_discovery_url,$client_id,$client_sec);
+        $config = KeycloakUtil::getOpenIDConnectDiscoveryConfiguration($openid_connect_discovery_url, $client_id, $client_sec);
 
         $token_endpoint = $config->token_endpoint;
 
@@ -22,8 +22,11 @@ class KeycloakUtil
             curl_setopt($r, CURLOPT_CAINFO, $cafile_path);
         }
 
+        $credentials = KeycloakUtil::getAuthCredentials($custos_credentials_uri, $client_id, $client_sec);
+
         // Assemble POST parameters for the request.
-        $post_fields = "client_id=admin-cli&username=" . urlencode($admin_username) . "&password=" . urlencode($admin_password) . "&grant_type=password";
+        $post_fields = "client_id=" . urlencode($client_id) . "&client_secret=" . urlencode($credentials->iam_client_secret) . "&username="
+            . urlencode($admin_username) . "&password=" . urlencode($admin_password) . "&grant_type=password";
 
         // Obtain and return the access token from the response.
         curl_setopt($r, CURLOPT_POST, true);
@@ -70,5 +73,32 @@ class KeycloakUtil
         return $json;
     }
 
+    public static function getAuthCredentials($custos_credentials_uri, $client_id, $client_secret)
+    {
+
+        $post_files = "?client_id=" . urlencode($client_id);
+        $url = $custos_credentials_uri . $post_files;
+
+        // TODO: cache the result of the request
+        $r = curl_init($url);
+
+        curl_setopt($r, CURLOPT_HTTPHEADER, array(
+            "Authorization: Basic " . base64_encode($client_id . ":" . $client_secret),
+        ));
+
+
+        curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
+        // Decode compressed responses.
+        curl_setopt($r, CURLOPT_ENCODING, 1);
 
+        $result = curl_exec($r);
+        if ($result == false) {
+            die("curl_exec() failed. Error: " . curl_error($r));
+        }
+
+        $json = json_decode($result);
+
+        // Log::debug("openid connect discovery configuration", array($json));
+        return $json;
+    }
 }