測試自訂使用者介面的權限

大多數 Cloud de Confiance by S3NS 資源都會公開 testIamPermissions() 方法,可讓您以程式輔助方式檢查目前已驗證的呼叫者,是否已獲得資源的一或多個特定 IAM 權限。testIamPermissions() 方法會將資源 ID 和一組權限視為輸入參數,並傳回已授予呼叫者的權限組合。

您可以使用 testIamPermissions() 方法,判斷使用者是否應有權存取網頁應用程式中的管理工具。舉例來說,您可以根據使用者的權限,使用這個方法決定是否要顯示資源的詳細資訊。 Cloud de Confiance

舉例來說,如要判斷目前已驗證的使用者是否擁有刪除專案的權限,請提供專案 ID (例如 foo-project) 和 resourcemanager.projects.delete 權限做為輸入參數,呼叫 projects.testIamPermissions() 方法。如果呼叫者已獲得 resourcemanager.projects.delete 權限,該權限會列在回應主體中。如果呼叫者沒有這個權限,回應主體中不會列出任何權限。

testIamPermissions() 方法適用於第三方圖形使用者介面 (GUI),這些介面必須根據已驗證使用者擁有查看權限的項目來顯示 Cloud de Confiance 資源。舉例來說,Cloud de Confiance 主控台會在內部使用 testIamPermissions() 方法,決定驗證後您可以看到的資源和功能。通常會為不同的使用者授予不同的權限,且 Cloud de Confiance 主控台會相應地隱藏或公開項目。

事前準備

必要的角色

測試權限時不需要 IAM 角色。

如何測試權限

這個範例說明如何測試 Cloud de Confiance 專案resourcemanager.projects.getresourcemanager.projects.delete 權限。如要測試其他 Cloud de Confiance 資源的權限,請使用每個資源公開的 testIamPermissions() 方法。舉例來說,您可以測試 Cloud Storage 值區的 IAM 權限。

C++

如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM C++ API 參考說明文件

如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name, std::vector<std::string> const& permissions) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.TestIamPermissions(name, permissions);
  if (!response) throw std::move(response).status();
  std::cout << "Permissions successfully tested: " << response->DebugString()
            << "\n";
}

C#

如要向 Resource Manager 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

IAM 會測試您用來產生憑證的服務帳戶權限。


using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static IList<String> TestIamPermissions(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        TestIamPermissionsRequest requestBody = new TestIamPermissionsRequest();
        var permissions = new List<string>() { "resourcemanager.projects.get", "resourcemanager.projects.delete" };
        requestBody.Permissions = new List<string>(permissions);
        var returnedPermissions = service.Projects.TestIamPermissions(requestBody, projectId).Execute().Permissions;

        return returnedPermissions;
    }
}

Java

如要向 Resource Manager 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

IAM 會測試您用來產生憑證的服務帳戶權限。

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.cloudresourcemanager.v3.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.v3.model.TestIamPermissionsRequest;
import com.google.api.services.cloudresourcemanager.v3.model.TestIamPermissionsResponse;
import com.google.api.services.iam.v1.IamScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class TestPermissions {

  // Tests if the caller has the listed permissions.
  public static void testPermissions(String projectId) {
    // projectId = "my-project-id"

    CloudResourceManager service = null;
    try {
      service = createCloudResourceManagerService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    List<String> permissionsList =
        Arrays.asList("resourcemanager.projects.get", "resourcemanager.projects.delete");

    TestIamPermissionsRequest requestBody =
        new TestIamPermissionsRequest().setPermissions(permissionsList);
    try {
      TestIamPermissionsResponse testIamPermissionsResponse =
          service.projects().testIamPermissions(projectId, requestBody).execute();

      System.out.println(
          "Of the permissions listed in the request, the caller has the following: "
              + testIamPermissionsResponse.getPermissions().toString());
    } catch (IOException e) {
      System.out.println("Unable to test permissions: \n" + e.toString());
    }
  }

  public static CloudResourceManager createCloudResourceManagerService()
      throws IOException, GeneralSecurityException {
    // Use the Application Default Credentials strategy for authentication. For more info, see:
    // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    CloudResourceManager service =
        new CloudResourceManager.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

如要向 Resource Manager 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

IAM 會測試您用來產生憑證的服務帳戶權限。

def test_permissions(project_id: str) -> List[str]:
    """Tests IAM permissions of currently authenticated user to a project."""

    projects_client = resourcemanager_v3.ProjectsClient()
    if not project_id.startswith("projects/"):
        project_id = "projects/" + project_id

    owned_permissions = projects_client.test_iam_permissions(
        resource=project_id,
        permissions=["resourcemanager.projects.get", "resourcemanager.projects.delete"],
    ).permissions

    print("Currently authenticated user has following permissions:", owned_permissions)
    return owned_permissions

REST

在這個範例中,使用者擁有 IAM 角色,可取得專案相關資訊,但無法刪除專案。

Resource Manager API 的 projects.testIamPermissions 方法會接受權限清單,並測試主體擁有哪些權限。

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Cloud de Confiance 專案 ID。專案 ID 為英數字串,例如 my-project

HTTP 方法和網址:

POST https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:testIamPermissions

JSON 要求主體:

{
  "permissions":  [
    "resourcemanager.projects.get",
    "resourcemanager.projects.delete"
  ]
}

如要傳送要求,請展開以下其中一個選項:

您應該會收到如下的 JSON 回應:

{
  "permissions": [
    "resourcemanager.projects.get"
  ]
}

後續步驟

瞭解如何授予、變更及撤銷主體的存取權