Test permissions for custom user interfaces Stay organized with collections Save and categorize content based on your preferences.
Most Google Cloud resources expose thetestIamPermissions() method, whichallows you to programmatically check whether the currently authenticated callerhas been granted one or more specific IAM permissions on theresource. ThetestIamPermissions() method takes a resource identifier and aset of permissions as input parameters, and returns the set of permissions thatthe caller is allowed.
You can use thetestIamPermissions() method to determine whether a user shouldhave access to an administrative tool in a web application. For example, you canuse this method to decide, based on the user's permissions, whether to displaydetailed information about a Google Cloud resource.
For example, to determine if the currently authenticated user has the permissionto delete a project, call theprojects.testIamPermissions()method by providing the project ID (such asfoo-project) and theresourcemanager.projects.delete permission as input parameters. If the callerhas been granted theresourcemanager.projects.delete permission, it will belisted in the response body. If the caller does not have this permission,the response body will list no permissions.
ThetestIamPermissions() method is intended for third-party graphicaluser interfaces (GUIs) that need to display Google Cloud resources basedon what the authenticated user has permissions to see. For example, theGoogle Cloud console internally uses thetestIamPermissions() method todetermine what resources and functionality are visible to you afterauthenticating. Different users are typically granted different permissions,and the Google Cloud console hides or exposes items accordingly.
Before you begin
Enable the Resource Manager API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Set up authentication.
Select the tab for how you plan to use the samples on this page:
C#
To use the .NET samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
C++
To use the C++ samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
Java
To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
Python
To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up ADC for a local development environment in the Google Cloud authentication documentation.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.
Required roles
No IAM role is required to test permissions.
How to test permissions
This example shows how to test theresourcemanager.projects.get andresourcemanager.projects.delete permissions for aGoogle Cloud project. Totest permissions for other Google Cloud resources, use thetestIamPermissions() method exposed by each resource. For example, you cantest the IAM permissions for aCloud Storage bucket.
C++
To learn how to install and use the client library for IAM, seeIAM client libraries. For more information, see theIAMC++ API reference documentation.
To authenticate to IAM, set up Application Default Credentials. For more information, seeBefore you begin.
namespaceiam=::google::cloud::iam_admin_v1;[](std::stringconst&name,std::vector<std::string>const&permissions){iam::IAMClientclient(iam::MakeIAMConnection());autoresponse=client.TestIamPermissions(name,permissions);if(!response)throwstd::move(response).status();std::cout <<"Permissions successfully tested: " <<response->DebugString() <<"\n";}C#
To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.
To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.
IAM tests the permissions of the service account that you are using to generate credentials.
usingSystem;usingSystem.Collections.Generic;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.CloudResourceManager.v1;usingGoogle.Apis.CloudResourceManager.v1.Data;publicpartialclassAccessManager{publicstaticIList<String>TestIamPermissions(stringprojectId){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);varservice=newCloudResourceManagerService(newCloudResourceManagerService.Initializer{HttpClientInitializer=credential});TestIamPermissionsRequestrequestBody=newTestIamPermissionsRequest();varpermissions=newList<string>(){"resourcemanager.projects.get","resourcemanager.projects.delete"};requestBody.Permissions=newList<string>(permissions);varreturnedPermissions=service.Projects.TestIamPermissions(requestBody,projectId).Execute().Permissions;returnreturnedPermissions;}}Java
To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.
To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.
IAM tests the permissions of the service account that you are using to generate credentials.
importcom.google.api.client.googleapis.javanet.GoogleNetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.cloudresourcemanager.v3.CloudResourceManager;importcom.google.api.services.cloudresourcemanager.v3.model.TestIamPermissionsRequest;importcom.google.api.services.cloudresourcemanager.v3.model.TestIamPermissionsResponse;importcom.google.api.services.iam.v1.IamScopes;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.security.GeneralSecurityException;importjava.util.Arrays;importjava.util.Collections;importjava.util.List;publicclassTestPermissions{// Tests if the caller has the listed permissions.publicstaticvoidtestPermissions(StringprojectId){// projectId = "my-project-id"CloudResourceManagerservice=null;try{service=createCloudResourceManagerService();}catch(IOException|GeneralSecurityExceptione){System.out.println("Unable to initialize service: \n"+e.toString());return;}List<String>permissionsList=Arrays.asList("resourcemanager.projects.get","resourcemanager.projects.delete");TestIamPermissionsRequestrequestBody=newTestIamPermissionsRequest().setPermissions(permissionsList);try{TestIamPermissionsResponsetestIamPermissionsResponse=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(IOExceptione){System.out.println("Unable to test permissions: \n"+e.toString());}}publicstaticCloudResourceManagercreateCloudResourceManagerService()throwsIOException,GeneralSecurityException{// Use the Application Default Credentials strategy for authentication. For more info, see:// https://cloud.google.com/docs/authentication/production#finding_credentials_automaticallyGoogleCredentialscredential=GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));CloudResourceManagerservice=newCloudResourceManager.Builder(GoogleNetHttpTransport.newTrustedTransport(),GsonFactory.getDefaultInstance(),newHttpCredentialsAdapter(credential)).setApplicationName("service-accounts").build();returnservice;}}Python
To authenticate to Resource Manager, set up Application Default Credentials. For more information, seeBefore you begin.
To learn how to install and use the client library for Resource Manager, seeResource Manager client libraries.
IAM tests the permissions of the service account that you are using to generate credentials.
deftest_permissions(project_id:str)->List[str]:"""Tests IAM permissions of currently authenticated user to a project."""projects_client=resourcemanager_v3.ProjectsClient()ifnotproject_id.startswith("projects/"):project_id="projects/"+project_idowned_permissions=projects_client.test_iam_permissions(resource=project_id,permissions=["resourcemanager.projects.get","resourcemanager.projects.delete"],).permissionsprint("Currently authenticated user has following permissions:",owned_permissions)returnowned_permissionsREST
In this example, the user has an IAM role that allows them toget information about a project, but not to delete projects.
The Resource Manager API'sprojects.testIamPermissions method accepts a list of permissions and tests which of the permissions a principal has.
Before using any of the request data, make the following replacements:
PROJECT_ID: Your Google Cloud projectID. Project IDs are alphanumeric strings, likemy-project.
HTTP method and URL:
POST https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:testIamPermissions
Request JSON body:
{ "permissions": [ "resourcemanager.projects.get", "resourcemanager.projects.delete" ]}To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:testIamPermissions"
PowerShell (Windows)
Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list. Save the request body in a file namedrequest.json, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:testIamPermissions" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open themethod reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and clickExecute.
You should receive a JSON response similar to the following:
{ "permissions": [ "resourcemanager.projects.get" ]}What's next
Learn how togrant, change, and revoke access to principals.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.