Testing permissions

Most Google Cloud resources expose the testIamPermissions() method, which allows you to check whether the currently authenticated caller has been granted one or more specific Cloud IAM permissions on the resource. The testIamPermissions() method takes a resource identifier and a set of permissions as input parameters, and returns the set of permissions that the caller is allowed.

For example, to determine if the currently authenticated user has the permission to delete a project, call the projects.testIamPermissions() method by providing the project ID (such as foo-project) and the resourcemanager.projects.delete permission as input parameters. If the caller has been granted the resourcemanager.projects.delete permission, it will be listed in the response body. If the caller does not have this permission, the response body will list no permissions.

The testIamPermissions() method is intended for third-party graphical user interfaces (GUIs) that need to display Google Cloud resources based on what the authenticated user has permissions to see. For example, the Cloud Console internally uses the testIamPermissions() method to determine what resources and functionality are visible to you after authenticating. Different users are typically granted different permissions, and the Cloud Console hides or exposes items accordingly.

How to test permissions

This example shows how to test the resourcemanager.projects.get and resourcemanager.projects.delete permissions for a Google Cloud project. To test permissions for other Google Cloud resources, use the testIamPermissions() method exposed by each resource. For example, you can test the Cloud IAM permissions for a Cloud Storage bucket.

REST API

See the Resource Manager API's projects.testIamPermissions() method for more information.

In this example, the user has a Cloud IAM role that allows them to get information about a project, but not to delete projects.

Request (substitute your Google Cloud project ID for [PROJECT_ID]):

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

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

Response:

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

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM C# API reference documentation .

Cloud IAM tests the permissions of the service account that you are using to generate credentials.

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

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Java API reference documentation .

Cloud IAM tests the permissions of the service account that you are using to generate credentials.
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudresourcemanager.CloudResourceManager;
import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsRequest;
import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsResponse;
import com.google.api.services.iam.v1.IamScopes;
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
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

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

Python

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Python API reference documentation .

Cloud IAM tests the permissions of the service account that you are using to generate credentials.
def test_permissions(project_id):
    """Tests IAM permissions of the caller"""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
        scopes=['https://www.googleapis.com/auth/cloud-platform'])
    service = googleapiclient.discovery.build(
        'cloudresourcemanager', 'v1', credentials=credentials)

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

    request = service.projects().testIamPermissions(
        resource=project_id, body=permissions)
    returnedPermissions = request.execute()
    print(returnedPermissions)
    return returnedPermissions

What's next

Learn how to grant, change, and revoke access to project members.

هل كانت هذه الصفحة مفيدة؟ يرجى تقييم أدائنا:

إرسال تعليقات حول...

Cloud IAM Documentation