測試權限
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
示範如何測試呼叫者是否擁有指定權限。
深入探索
如需包含這個程式碼範例的詳細說明文件,請參閱下列內容:
程式碼範例
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page provides code samples in C++, C#, Java, and Python that demonstrate how to test if a caller has specific IAM permissions.\u003c/p\u003e\n"],["\u003cp\u003eThe examples use the \u003ccode\u003eTestIamPermissions\u003c/code\u003e method to check for permissions such as \u003ccode\u003eresourcemanager.projects.get\u003c/code\u003e and \u003ccode\u003eresourcemanager.projects.delete\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eTo use these code samples, you must install and use the appropriate IAM client library for your language.\u003c/p\u003e\n"],["\u003cp\u003eApplication Default Credentials (ADC) must be set up to authenticate and use the code samples locally.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples provide specific language implementations and references to related documentation to test permissions.\u003c/p\u003e\n"]]],[],null,["# Test permissions\n\nDemonstrates testing whether the caller has specified permissions.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Test permissions for custom user interfaces](/iam/docs/testing-permissions)\n\nCode sample\n-----------\n\n### C++\n\n\nTo learn how to install and use the client library for IAM, see\n[IAM client libraries](/iam/docs/reference/libraries).\n\n\nFor more information, see the\n[IAM C++ API\nreference documentation](/cpp/docs/reference/iam/latest).\n\n\nTo authenticate to IAM, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n namespace iam = ::google::cloud::iam_admin_v1;\n [](std::string const& name, std::vector\u003cstd::string\u003e const& permissions) {\n iam::IAMClient client(iam::MakeIAMConnection());\n auto response = client.TestIamPermissions(name, permissions);\n if (!response) throw std::move(response).status();\n std::cout \u003c\u003c \"Permissions successfully tested: \" \u003c\u003c response-\u003eDebugString()\n \u003c\u003c \"\\n\";\n }\n\n### C#\n\n\nTo learn how to install and use the client library for IAM, see\n[IAM client libraries](/iam/docs/reference/libraries).\n\n\nFor more information, see the\n[IAM C# API\nreference documentation](https://developers.google.com/api-client-library/dotnet/apis/iam/v1).\n\n\nTo authenticate to IAM, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n using System;\n using System.Collections.Generic;\n using https://cloud.google.com/dotnet/docs/reference/Google.Apis/latest/Google.Apis.Auth.OAuth2.html;\n using Google.Apis.CloudResourceManager.v1;\n using Google.Apis.CloudResourceManager.v1.Data;\n\n public partial class AccessManager\n {\n public static IList\u003cString\u003e TestIamPermissions(string projectId)\n {\n var credential = https://cloud.google.com/dotnet/docs/reference/Google.Apis/latest/Google.Apis.Auth.OAuth2.GoogleCredential.html.https://cloud.google.com/dotnet/docs/reference/Google.Apis/latest/Google.Apis.Auth.OAuth2.GoogleCredential.html#Google_Apis_Auth_OAuth2_GoogleCredential_GetApplicationDefault()\n .https://cloud.google.com/dotnet/docs/reference/Google.Apis/latest/Google.Apis.Auth.OAuth2.GoogleCredential.html#Google_Apis_Auth_OAuth2_GoogleCredential_CreateScoped_System_Collections_Generic_IEnumerable_System_String__(CloudResourceManagerService.Scope.CloudPlatform);\n var service = new CloudResourceManagerService(\n new CloudResourceManagerService.Initializer\n {\n HttpClientInitializer = credential\n });\n\n TestIamPermissionsRequest requestBody = new TestIamPermissionsRequest();\n var permissions = new List\u003cstring\u003e() { \"resourcemanager.projects.get\", \"resourcemanager.projects.delete\" };\n requestBody.Permissions = new List\u003cstring\u003e(permissions);\n var returnedPermissions = service.Projects.TestIamPermissions(requestBody, projectId).Execute().Permissions;\n\n return returnedPermissions;\n }\n }\n\n### Java\n\n\nTo learn how to install and use the client library for IAM, see\n[IAM client libraries](/iam/docs/reference/libraries).\n\n\nFor more information, see the\n[IAM Java API\nreference documentation](https://developers.google.com/api-client-library/java/apis/iam/v1).\n\n\nTo authenticate to IAM, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.api.client.googleapis.javanet.https://cloud.google.com/java/docs/reference/google-api-client/latest/com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.html;\n import com.google.api.client.json.gson.https://cloud.google.com/java/docs/reference/google-http-client/latest/com.google.api.client.json.gson.GsonFactory.html;\n import com.google.api.services.cloudresourcemanager.v3.CloudResourceManager;\n import com.google.api.services.cloudresourcemanager.v3.model.TestIamPermissionsRequest;\n import com.google.api.services.cloudresourcemanager.v3.model.TestIamPermissionsResponse;\n import com.google.api.services.iam.v1.IamScopes;\n import com.google.auth.http.https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.http.HttpCredentialsAdapter.html;\n import com.google.auth.oauth2.https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.GoogleCredentials.html;\n import java.io.IOException;\n import java.security.GeneralSecurityException;\n import java.util.Arrays;\n import java.util.Collections;\n import java.util.List;\n\n public class TestPermissions {\n\n // Tests if the caller has the listed permissions.\n public static void testPermissions(String projectId) {\n // projectId = \"my-project-id\"\n\n CloudResourceManager service = null;\n try {\n service = createCloudResourceManagerService();\n } catch (IOException | GeneralSecurityException e) {\n System.out.println(\"Unable to initialize service: \\n\" + e.toString());\n return;\n }\n\n List\u003cString\u003e permissionsList =\n Arrays.asList(\"resourcemanager.projects.get\", \"resourcemanager.projects.delete\");\n\n TestIamPermissionsRequest requestBody =\n new TestIamPermissionsRequest().setPermissions(permissionsList);\n try {\n TestIamPermissionsResponse testIamPermissionsResponse =\n service.projects().testIamPermissions(projectId, requestBody).execute();\n\n System.out.println(\n \"Of the permissions listed in the request, the caller has the following: \"\n + testIamPermissionsResponse.getPermissions().toString());\n } catch (IOException e) {\n System.out.println(\"Unable to test permissions: \\n\" + e.toString());\n }\n }\n\n public static CloudResourceManager createCloudResourceManagerService()\n throws IOException, GeneralSecurityException {\n // Use the Application Default Credentials strategy for authentication. For more info, see:\n // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically\n https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.GoogleCredentials.html credential =\n https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.GoogleCredentials.html.https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.oauth2.GoogleCredentials.html#com_google_auth_oauth2_GoogleCredentials_getApplicationDefault__()\n .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));\n\n CloudResourceManager service =\n new CloudResourceManager.Builder(\n https://cloud.google.com/java/docs/reference/google-api-client/latest/com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.html.https://cloud.google.com/java/docs/reference/google-api-client/latest/com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.html#com_google_api_client_googleapis_javanet_GoogleNetHttpTransport_newTrustedTransport__(),\n https://cloud.google.com/java/docs/reference/google-http-client/latest/com.google.api.client.json.gson.GsonFactory.html.https://cloud.google.com/java/docs/reference/google-http-client/latest/com.google.api.client.json.gson.GsonFactory.html#com_google_api_client_json_gson_GsonFactory_getDefaultInstance__(),\n new https://cloud.google.com/java/docs/reference/google-auth-library/latest/com.google.auth.http.HttpCredentialsAdapter.html(credential))\n .setApplicationName(\"service-accounts\")\n .build();\n return service;\n }\n }\n\n### Python\n\n\nTo learn how to install and use the client library for IAM, see\n[IAM client libraries](/iam/docs/reference/libraries).\n\n\nFor more information, see the\n[IAM Python API\nreference documentation](https://developers.google.com/api-client-library/python/apis/iam/v1).\n\n\nTo authenticate to IAM, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n def test_permissions(project_id: str) -\u003e List[str]:\n \"\"\"Tests IAM permissions of currently authenticated user to a project.\"\"\"\n\n projects_client = resourcemanager_v3.ProjectsClient()\n if not project_id.startswith(\"projects/\"):\n project_id = \"projects/\" + project_id\n\n owned_permissions = projects_client.test_iam_permissions(\n resource=project_id,\n permissions=[\"resourcemanager.projects.get\", \"resourcemanager.projects.delete\"],\n ).permissions\n\n print(\"Currently authenticated user has following permissions:\", owned_permissions)\n return owned_permissions\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=iam)."]]