Controlling access to Cloud Healthcare API resources

This page describes how to control access to Cloud Healthcare API datasets and data stores using Cloud Identity and Access Management (IAM) permissions. Cloud IAM lets you control who has access to your datasets and data stores. To learn more about Cloud IAM for the Cloud Healthcare API, see Access control.

Overview of Cloud Identity and Access Management policy

Access to a resource is managed through a Cloud IAM policy. A policy contains an array, called bindings. This array contains a collection of bindings, which are associations between members, such as a user account or service account, and a role. Policies are represented using JSON or YAML.

Here is an example policy where user-1@example.com has been granted the roles/healthcare.datasetAdmin role, and user-2@example.com and service-account-13@appspot.gserviceaccount.com have been granted the roles/healthcare.datasetViewer role:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

To update a policy for a resource, use the read-modify-write pattern. This means that there are no separate methods for creating, modifying, and revoking user access. Instead, to update a policy, follow these steps:

  1. Read the current policy by calling the resource's getIamPolicy() method. For example, to read a dataset's current policy, call projects.locations.datasets.getIamPolicy.
  2. Edit the returned policy, either by using a text editor or programmatically, to add or remove any applicable members and their role grants.
  3. Write the updated policy by calling the resource's setIamPolicy() method. For example, to write a dataset's updated policy, call projects.locations.datasets.setIamPolicy.

Using Cloud Identity and Access Management with datasets

The following sections show how to get, modify, and set a policy for a dataset. These sections use the following example policy as a starting point:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Getting a policy

The following samples show how to read a dataset-level Cloud IAM policy. For more information, see projects.locations.datasets.getIamPolicy.

curl command

To read the Cloud IAM policy for a dataset, make a GET request and provide the name of the dataset and an access token. The following sample shows a GET request using curl.

curl -X GET \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID:getIamPolicy"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

PowerShell

To view the Cloud IAM policy for a dataset, make a GET request and provide the name of the dataset and an access token. The following sample shows a GET request using Windows PowerShell.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID:getIamPolicy" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Console

To view the Cloud IAM policy for a dataset:
  1. In the GCP Console, go to the Datasets page.

    Go to the Datasets page

  2. Select a dataset and then click Show info panel.
  3. To view the members assigned to a role, expand the role.

GCLOUD COMMAND

To view the Cloud IAM policy for a dataset, run the gcloud beta healthcare datasets get-iam-policy command. Specify the dataset name and the location.

gcloud beta healthcare datasets get-iam-policy DATASET_ID \
    --location=REGION 

If the request is successful, the bindings are displayed.

bindings:
- members:
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.datasetViewer
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// datasetIAMPolicy gets the dataset's IAM policy.
func datasetIAMPolicy(w io.Writer, projectID, location, datasetID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	datasetsService := healthcareService.Projects.Locations.Datasets

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID)

	policy, err := datasetsService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)
	}

	fmt.Fprintf(w, "IAM Policy etag: %v\n", policy.Etag)
	return nil
}

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Policy;
import java.io.IOException;
import java.util.Collections;

public class DatasetGetIamPolicy {
  private static final String DATASET_NAME = "projects/%s/locations/%s/datasets/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void datasetGetIamPolicy(String datasetName) throws IOException {
    // String datasetName =
    //     String.format(DATASET_NAME, "your-project-id", "your-region-id", "your-dataset-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Create request and configure any parameters.
    Datasets.GetIamPolicy request =
        client.projects().locations().datasets().getIamPolicy(datasetName);

    // Execute the request and process the results.
    Policy policy = request.execute();
    System.out.println("Dataset IAMPolicy retrieved: \n" + policy.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1beta1');

const getDatasetIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {resource_};

  const dataset = await healthcare.projects.locations.datasets.getIamPolicy(
    request
  );
  console.log(
    'Got dataset IAM policy:',
    JSON.stringify(dataset.data, null, 2)
  );
};

getDatasetIamPolicy();

Python

def get_dataset_iam_policy(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id):
    """Gets the IAM policy for the specified dataset."""
    client = get_client(service_account_json)
    dataset_name = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)

    request = client.projects().locations().datasets().getIamPolicy(
        resource=dataset_name)
    response = request.execute()

    print('etag: {}'.format(response.get('name')))
    return response

Modifying a policy

The following samples grant a new user the roles/healthcare.datasetViewer role.

Console

To set a dataset-level Cloud IAM policy:
  1. In the GCP Console, go to the Datasets page.

    Go to the Datasets page

  2. Select the dataset that you want to set a policy for and then click Show info panel.
  3. Click Add member.
  4. In the New members field, enter one or more identities that need access to the dataset.
  5. In the Select a role list, under Cloud Healthcare, select the permission that you want to grant. For example, Healthcare Dataset Viewer.
  6. Click Save.

GCLOUD COMMAND

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.datasetViewer binding:

{
  "role":"roles/healthcare.datasetViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, run the appropriate set-iam-policy command to make the changes. To set a dataset-level policy, run the gcloud beta healthcare datasets set-iam-policy command. Specify the dataset name, the location, and the path to the policy file that you created.

gcloud beta healthcare datasets set-iam-policy DATASET_ID \
    --location=REGION \
    POLICY_FILE_NAME 

If the request is successful, the dataset name and the bindings are displayed.

Updated IAM policy for dataset [DATASET_ID].
bindings:
- members:
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.datasetAdmin
  - user:user-1@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.datasetViewer
etag: bytes
version: VERSION_NUMBER

curl command

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.datasetViewer binding:

{
  "role":"roles/healthcare.datasetViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, call projects.locations.datasets.setIamPolicy to make the updates.

To set a dataset-level Cloud IAM policy, make a POST request and provide the name of the dataset, the policy, and an access token. The following sample shows a POST request using curl to grant a new user the existing roles/healthcare.datasetViewer role.

The policy can be written directly in the request, as shown here, or it can be passed in as a JSON or YAML file. For examples of how to format a policy as JSON or YAML, see Policy.
curl -X POST \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.datasetAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.datasetViewer',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID:setIamPolicy"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

PowerShell

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.datasetViewer binding:

{
  "role":"roles/healthcare.datasetViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, call projects.locations.datasets.setIamPolicy to make the updates.

To set a dataset-level Cloud IAM policy, make a POST request and provide the name of the dataset, the policy, and an access token. The following sample shows a POST request using Windows PowerShell to grant a new user the existing roles/healthcare.datasetViewer role.

The policy can be written directly in the request, as shown here, or it can be passed in as a JSON or YAML file. For examples of how to format a policy as JSON or YAML, see Policy.
$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.datasetAdmin',
          'members': [
            'user:user-1@example.com'
          ]
        },
        {
          'role': 'roles/healthcare.datasetViewer',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID:setIamPolicy" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.datasetAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.datasetViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// setDatasetIAMPolicy sets an IAM policy for the dataset.
func setDatasetIAMPolicy(w io.Writer, projectID, location, datasetID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	datasetsService := healthcareService.Projects.Locations.Datasets

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID)

	policy, err := datasetsService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)
	}

	policy.Bindings = append(policy.Bindings, &healthcare.Binding{
		Members: []string{"user:example@example.com"},
		Role:    "roles/viewer",
	})

	req := &healthcare.SetIamPolicyRequest{
		Policy: policy,
	}

	policy, err = datasetsService.SetIamPolicy(name, req).Do()
	if err != nil {
		return fmt.Errorf("SetIamPolicy: %v", err)
	}

	fmt.Fprintf(w, "IAM Policy etag: %v", policy.Etag)
	return nil
}

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Binding;
import com.google.api.services.healthcare.v1beta1.model.Policy;
import com.google.api.services.healthcare.v1beta1.model.SetIamPolicyRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class DatasetSetIamPolicy {
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void datasetSetIamPolicy(String datasetName) throws IOException {
    // String datasetName =
    //     String.format(DATASET_NAME, "your-project-id", "your-region-id", "your-dataset-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Configure the IAMPolicy to apply to the dataset.
    // For more information on understanding IAM roles, see the following:
    // https://cloud.google.com/iam/docs/understanding-roles
    Binding binding =
        new Binding()
            .setRole("roles/healthcare.datasetViewer")
            .setMembers(Arrays.asList("domain:google.com"));
    Policy policy = new Policy().setBindings(Arrays.asList(binding));
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest().setPolicy(policy);

    // Create request and configure any parameters.
    Datasets.SetIamPolicy request =
        client.projects().locations().datasets().setIamPolicy(datasetName, policyRequest);

    // Execute the request and process the results.
    Policy updatedPolicy = request.execute();
    System.out.println("Dataset policy has been updated: " + updatedPolicy.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1beta1');

const setDatasetIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const member = 'user:example@gmail.com';
  // const role = 'roles/healthcare.datasetViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: member,
            role: role,
          },
        ],
      },
    },
  };

  const dataset = await healthcare.projects.locations.datasets.setIamPolicy(
    request
  );
  console.log(
    'Set dataset IAM policy:',
    JSON.stringify(dataset.data, null, 2)
  );
};

setDatasetIamPolicy();

Python

def set_dataset_iam_policy(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        member,
        role,
        etag=None):
    """Sets the IAM policy for the specified dataset.

        A single member will be assigned a single role. A member can be any of:

        - allUsers, that is, anyone
        - allAuthenticatedUsers, anyone authenticated with a Google account
        - user:email, as in 'user:somebody@example.com'
        - group:email, as in 'group:admins@example.com'
        - domain:domainname, as in 'domain:example.com'
        - serviceAccount:email,
            as in 'serviceAccount:my-other-app@appspot.gserviceaccount.com'

        A role can be any IAM role, such as 'roles/viewer', 'roles/owner',
        or 'roles/editor'
    """
    client = get_client(service_account_json)
    dataset_name = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)

    policy = {
        "bindings": [
            {
              "role": role,
              "members": [
                member
              ]
            }
        ]
    }

    if etag is not None:
        policy['etag'] = etag

    request = client.projects().locations().datasets().setIamPolicy(
        resource=dataset_name, body={'policy': policy})
    response = request.execute()

    print('etag: {}'.format(response.get('name')))
    print('bindings: {}'.format(response.get('bindings')))
    return response

Using Cloud Identity and Access Management with DICOM stores

The following sections show how to get, modify, and set a policy for a DICOM store. These sections use the following example policy as a starting point:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Getting a policy

The following samples show how to read a DICOM store-level Cloud IAM policy. For more information, see projects.locations.datasets.dicomStores.getIamPolicy.

Console

To view the Cloud IAM policy for a DICOM store:

  1. In the GCP Console, go to the Datasets page.

    Go to the Datasets page

  2. Click the ID of the dataset that contains the DICOM store and then select the DICOM store that you want to get a policy for.
  3. Click Show info panel.
  4. To view the members assigned to a role, expand the role.

GCLOUD COMMAND

To view the Cloud IAM policy for a DICOM store, run the gcloud beta healthcare dicom-stores get-iam-policy command. Specify the DICOM store name, the dataset name, and the location.

gcloud beta healthcare dicom-stores get-iam-policy DICOM_STORE_ID \
    --dataset=DATASET_ID \
    --location=REGION 

If the request is successful, the bindings are displayed.

bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.dicomStoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.dicomViewer
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// getDICOMIAMPolicy gets the DICOM store's IAM policy.
func getDICOMIAMPolicy(w io.Writer, projectID, location, datasetID, dicomStoreID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	dicomService := healthcareService.Projects.Locations.Datasets.DicomStores

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/dicomStores/%s", projectID, location, datasetID, dicomStoreID)

	policy, err := dicomService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)
	}

	fmt.Fprintf(w, "IAM Policy etag: %v\n", policy.Etag)
	return nil
}

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.DicomStores;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Policy;
import java.io.IOException;
import java.util.Collections;

public class DicomStoreGetIamPolicy {
  private static final String DATASET_NAME = "projects/%s/locations/%s/datasets/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void dicomStoreGetIamPolicy(String dicomStoreName) throws IOException {
    // String dicomStoreName =
    //    String.format(
    //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Create request and configure any parameters.
    DicomStores.GetIamPolicy request =
        client.projects().locations().datasets().dicomStores().getIamPolicy(dicomStoreName);

    // Execute the request and process the results.
    Policy policy = request.execute();
    System.out.println("DICOM store IAMPolicy retrieved: \n" + policy.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1beta1');

const getDicomStoreIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const dicomStoreId = 'my-dicom-store';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`;
  const request = {resource_};

  const dicomStore = await healthcare.projects.locations.datasets.dicomStores.getIamPolicy(
    request
  );
  console.log(
    'Got DICOM store IAM policy:',
    JSON.stringify(dicomStore.data, null, 2)
  );
};

getDicomStoreIamPolicy();

Python

def get_dicom_store_iam_policy(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        dicom_store_id):
    """Gets the IAM policy for the specified dicom store."""
    client = get_client(service_account_json)
    dicom_store_parent = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)
    dicom_store_name = '{}/dicomStores/{}'.format(
        dicom_store_parent, dicom_store_id)

    request = client.projects().locations().datasets().dicomStores(
        ).getIamPolicy(resource=dicom_store_name)
    response = request.execute()

    print('etag: {}'.format(response.get('name')))
    return response

curl command

To read the Cloud IAM policy for a DICOM store, make a GET request and provide the name of the dataset, the name of the DICOM store, and an access token. The following sample shows a GET request using curl.

curl -X GET \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/dicomStores/DICOM_STORE_ID:getIamPolicy"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

PowerShell

To read the Cloud IAM policy for a DICOM store, make a GET request and provide the name of the dataset, the name of the DICOM store, and an access token. The following sample shows a GET request using Windows PowerShell.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/dicomStores/DICOM_STORE_ID:getIamPolicy" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Modifying a policy

The following samples grant a new user the roles/healthcare.dicomViewer role. For more information, see projects.locations.datasets.dicomStores.setIamPolicy.

Console

To set a DICOM store-level Cloud IAM policy:

  1. In the GCP Console, go to the Datasets page.

    Go to the Datasets page

  2. Click the ID of the dataset that contains the DICOM store and then select the DICOM store that you want to set a policy for.
  3. Click Show info panel.
  4. Click Add member.
  5. In the New members field, enter one or more identities that need access to the DICOM store.
  6. In the Select a role list, under Cloud Healthcare, select the permission that you want to grant. For example, Healthcare DICOM Store Viewer.
  7. Click Save.

GCLOUD COMMAND

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.dicomViewer binding:

{
  "role":"roles/healthcare.dicomViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, run the appropriate set-iam-policy command to make the changes. To set a DICOM store-level policy, run the gcloud beta healthcare dicom-stores set-iam-policy command. Specify the DICOM store name, the dataset name, the location, and the path to the policy file that you created.

gcloud beta healthcare dicom-stores set-iam-policy DICOM_STORE_ID \
    --dataset=DATASET_ID \
    --location=REGION \
    POLICY_FILE_NAME 

If the request is successful, the DICOM store name and the bindings are displayed.

Updated IAM policy for dicomStore [DICOM_STORE_ID].
bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.dicomStoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.dicomViewer
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// setDICOMIAMPolicy sets the DICOM store's IAM policy.
func setDICOMIAMPolicy(w io.Writer, projectID, location, datasetID, dicomStoreID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	dicomService := healthcareService.Projects.Locations.Datasets.DicomStores

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/dicomStores/%s", projectID, location, datasetID, dicomStoreID)

	policy, err := dicomService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)
	}

	policy.Bindings = append(policy.Bindings, &healthcare.Binding{
		Members: []string{"user:example@example.com"},
		Role:    "roles/viewer",
	})

	req := &healthcare.SetIamPolicyRequest{
		Policy: policy,
	}

	policy, err = dicomService.SetIamPolicy(name, req).Do()
	if err != nil {
		return fmt.Errorf("SetIamPolicy: %v", err)
	}

	fmt.Fprintf(w, "IAM Policy etag: %v\n", policy.Etag)
	return nil
}

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.DicomStores;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Binding;
import com.google.api.services.healthcare.v1beta1.model.Policy;
import com.google.api.services.healthcare.v1beta1.model.SetIamPolicyRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class DicomStoreSetIamPolicy {
  private static final String DICOM_NAME = "projects/%s/locations/%s/datasets/%s/dicomStores/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void dicomStoreSetIamPolicy(String dicomStoreName) throws IOException {
    // String dicomStoreName =
    //    String.format(
    //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Configure the IAMPolicy to apply to the store.
    // For more information on understanding IAM roles, see the following:
    // https://cloud.google.com/iam/docs/understanding-roles
    Binding binding =
        new Binding()
            .setRole("roles/healthcare.dicomStoreAdmin")
            .setMembers(Arrays.asList("domain:google.com"));
    Policy policy = new Policy().setBindings(Arrays.asList(binding));
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest().setPolicy(policy);

    // Create request and configure any parameters.
    DicomStores.SetIamPolicy request =
        client
            .projects()
            .locations()
            .datasets()
            .dicomStores()
            .setIamPolicy(dicomStoreName, policyRequest);

    // Execute the request and process the results.
    Policy updatedPolicy = request.execute();
    System.out.println("DICOM policy has been updated: " + updatedPolicy.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1beta1');

const setDicomStoreIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const dicomStoreId = 'my-dicom-store';
  // const member = 'user:example@gmail.com';
  // const role = 'roles/healthcare.dicomStoreViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: member,
            role: role,
          },
        ],
      },
    },
  };

  const dicomStore = await healthcare.projects.locations.datasets.dicomStores.setIamPolicy(
    request
  );
  console.log(
    'Set DICOM store IAM policy:',
    JSON.stringify(dicomStore.data, null, 2)
  );
};

setDicomStoreIamPolicy();

Python

def set_dicom_store_iam_policy(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        dicom_store_id,
        member,
        role,
        etag=None):
    """Sets the IAM policy for the specified dicom store.

        A single member will be assigned a single role. A member can be any of:

        - allUsers, that is, anyone
        - allAuthenticatedUsers, anyone authenticated with a Google account
        - user:email, as in 'user:somebody@example.com'
        - group:email, as in 'group:admins@example.com'
        - domain:domainname, as in 'domain:example.com'
        - serviceAccount:email,
            as in 'serviceAccount:my-other-app@appspot.gserviceaccount.com'

        A role can be any IAM role, such as 'roles/viewer', 'roles/owner',
        or 'roles/editor'
    """
    client = get_client(service_account_json)
    dicom_store_parent = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)
    dicom_store_name = '{}/dicomStores/{}'.format(
        dicom_store_parent, dicom_store_id)

    policy = {
        "bindings": [
            {
              "role": role,
              "members": [
                member
              ]
            }
        ]
    }

    if etag is not None:
        policy['etag'] = etag

    request = client.projects().locations().datasets().dicomStores(
        ).setIamPolicy(resource=dicom_store_name, body={'policy': policy})
    response = request.execute()

    print('etag: {}'.format(response.get('name')))
    print('bindings: {}'.format(response.get('bindings')))
    return response

curl command

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.dicomViewer binding:

{
  "role":"roles/healthcare.dicomViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, call projects.locations.datasets.dicomStores.setIamPolicy to make the updates.

To set a DICOM store-level Cloud IAM policy, make a POST request and provide the name of the dataset, the name of the DICOM store, the policy, and an access token. The following sample shows a POST request using curl to grant a new user the existing roles/healthcare.dicomViewer role.

The policy can be written directly in the request, as shown here, or it can be passed in as a JSON or YAML file. For examples of how to format a policy as JSON or YAML, see Policy.
curl -X POST \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.dicomStoreAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.dicomViewer',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/dicomStores/DICOM_STORE_ID:setIamPolicy"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

PowerShell

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.dicomViewer binding:

{
  "role":"roles/healthcare.dicomViewer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, call projects.locations.datasets.dicomStores.setIamPolicy to make the updates.

To set a DICOM store-level Cloud IAM policy, make a POST request and provide the name of the dataset, the name of the DICOM store, the policy, and an access token. The following sample shows a POST request using Windows PowerShell to grant a new user the existing roles/healthcare.dicomViewer role.

The policy can be written directly in the request, as shown here, or it can be passed in as a JSON or YAML file. For examples of how to format a policy as JSON or YAML, see Policy.
$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.dicomStoreAdmin',
          'members': [
            'user:user-1@example.com',
          ]
        },
        {
          'role': 'roles/healthcare.dicomViewer',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/dicomStores/DICOM_STORE_ID:setIamPolicy" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.dicomStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.dicomViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

Using Cloud Identity and Access Management with FHIR stores

The following sections show how to get, modify, and set a policy for a FHIR store. These sections use the following example policy as a starting point:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Getting a policy

The following samples show how to read a FHIR store-level Cloud IAM policy. For more information, see projects.locations.datasets.fhirStores.getIamPolicy.

Console

To view the Cloud IAM policy for a FHIR store:

  1. In the GCP Console, go to the Datasets page.

    Go to the Datasets page

  2. Click the ID of the dataset that contains the FHIR store and then select the FHIR store that you want to get a policy for.
  3. Click Show info panel.
  4. To view the members assigned to a role, expand the role.

GCLOUD COMMAND

To view the Cloud IAM policy for a FHIR store, run the gcloud beta healthcare fhir-stores get-iam-policy command. Specify FHIR store name, the dataset name, and the location.

gcloud beta healthcare fhir-stores get-iam-policy FHIR_STORE_ID \
    --dataset=DATASET_ID \
    --location=REGION 

If the request is successful, the bindings are displayed.

bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.fhirStoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.fhirResourceReader
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// getFHIRIAMPolicy gets the FHIR store's IAM policy.
func getFHIRIAMPolicy(w io.Writer, projectID, location, datasetID, fhirStoreID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s", projectID, location, datasetID, fhirStoreID)

	policy, err := fhirService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)
	}

	fmt.Fprintf(w, "IAM Policy etag: %v\n", policy.Etag)
	return nil
}

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Policy;
import java.io.IOException;
import java.util.Collections;

public class FhirStoreGetIamPolicy {
  private static final String FHIR_NAME = "projects/%s/locations/%s/datasets/%s/fhirStores/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirStoreGetIamPolicy(String fhirStoreName) throws IOException {
    // String fhirStoreName =
    //    String.format(
    //        FHIR_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-fhir-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Create request and configure any parameters.
    FhirStores.GetIamPolicy request =
        client.projects().locations().datasets().fhirStores().getIamPolicy(fhirStoreName);

    // Execute the request and process the results.
    Policy policy = request.execute();
    System.out.println("FHIR store IAMPolicy retrieved: \n" + policy.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1beta1');

const getFhirStoreIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const fhirStoreId = 'my-fhir-store';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;
  const request = {resource_};

  const fhirStore = await healthcare.projects.locations.datasets.fhirStores.getIamPolicy(
    request
  );
  console.log(
    'Got FHIR store IAM policy:',
    JSON.stringify(fhirStore.data, null, 2)
  );
};

getFhirStoreIamPolicy();

Python

def get_fhir_store_iam_policy(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id):
    """Gets the IAM policy for the specified FHIR store."""
    client = get_client(service_account_json)
    fhir_store_parent = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)
    fhir_store_name = '{}/fhirStores/{}'.format(
        fhir_store_parent, fhir_store_id)

    request = client.projects().locations().datasets().fhirStores(
        ).getIamPolicy(resource=fhir_store_name)
    response = request.execute()

    print('etag: {}'.format(response.get('name')))
    return response

curl command

To read the Cloud IAM policy for a FHIR store, make a POST request and provide the name of the dataset, the name of the FHIR store, and an access token. The following sample shows a POST request using curl.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID:getIamPolicy"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

PowerShell

To read the Cloud IAM policy for a FHIR store, make a POST request and provide the name of the dataset, the name of the FHIR store, and an access token. The following sample shows a POST request using Windows PowerShell.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID:getIamPolicy" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceReader",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Modifying a policy

The following samples grant a new user the roles/healthcare.fhirResourceReader role. For more information, see projects.locations.datasets.fhirStores.setIamPolicy.

Console

To set a FHIR store-level Cloud IAM policy:

  1. In the GCP Console, go to the Datasets page.

    Go to the Datasets page

  2. Click the ID of the dataset that contains the FHIR store and then select the FHIR store that you want to set a policy for.
  3. Click Show info panel.
  4. Click Add member.
  5. In the New members field, enter one or more identities that need access to the FHIR store.
  6. In the Select a role list, under Cloud Healthcare, select the permission that you want to grant. For example, Healthcare FHIR Resource Reader.
  7. Click Save.

GCLOUD COMMAND

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.fhirResourceReader binding:

{
  "role":"roles/healthcare.fhirResourceReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, run the appropriate set-iam-policy command to make the changes. To set a FHIR store-level policy, run the gcloud beta healthcare fhir-stores set-iam-policy command. Specify the FHIR store name, the dataset name, the location, and the path to the policy file that you created.

gcloud beta healthcare fhir-stores set-iam-policy FHIR_STORE_ID \
    --dataset=DATASET_ID \
    --location=REGION \
    POLICY_FILE_NAME
  If the request is successful, the FHIR store name and the bindings are displayed.
Updated IAM policy for fhirStore [FHIR_STORE_ID].
bindings:
- members:
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.fhirResourceReader
etag: bytes
version: VERSION_NUMBER

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// setFHIRIAMPolicy sets the FHIR store's IAM policy.
func setFHIRIAMPolicy(w io.Writer, projectID, location, datasetID, fhirStoreID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	fhirService := healthcareService.Projects.Locations.Datasets.FhirStores

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/fhirStores/%s", projectID, location, datasetID, fhirStoreID)

	policy, err := fhirService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)
	}

	policy.Bindings = append(policy.Bindings, &healthcare.Binding{
		Members: []string{"user:example@example.com"},
		Role:    "roles/viewer",
	})

	req := &healthcare.SetIamPolicyRequest{
		Policy: policy,
	}

	policy, err = fhirService.SetIamPolicy(name, req).Do()
	if err != nil {
		return fmt.Errorf("SetIamPolicy: %v", err)
	}

	fmt.Fprintf(w, "IAM Policy version: %v\n", policy.Version)
	return nil
}

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.FhirStores;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Binding;
import com.google.api.services.healthcare.v1beta1.model.Policy;
import com.google.api.services.healthcare.v1beta1.model.SetIamPolicyRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class FhirStoreSetIamPolicy {
  private static final String FHIR_NAME = "projects/%s/locations/%s/datasets/%s/fhirStores/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void fhirStoreSetIamPolicy(String fhirStoreName) throws IOException {
    // String fhirStoreName =
    //    String.format(
    //        FHIR_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-fhir-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Configure the IAMPolicy to apply to the store.
    // For more information on understanding IAM roles, see the following:
    // https://cloud.google.com/iam/docs/understanding-roles
    Binding binding =
        new Binding()
            .setRole("roles/healthcare.fhirResourceReader")
            .setMembers(Arrays.asList("domain:google.com"));
    Policy policy = new Policy().setBindings(Arrays.asList(binding));
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest().setPolicy(policy);

    // Create request and configure any parameters.
    FhirStores.SetIamPolicy request =
        client
            .projects()
            .locations()
            .datasets()
            .fhirStores()
            .setIamPolicy(fhirStoreName, policyRequest);

    // Execute the request and process the results.
    Policy updatedPolicy = request.execute();
    System.out.println("FHIR policy has been updated: " + updatedPolicy.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1beta1');

const setFhirStoreIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const member = 'user:example@gmail.com';
  // const role = 'roles/healthcare.fhirStoreViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/fhirStores/${fhirStoreId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: member,
            role: role,
          },
        ],
      },
    },
  };

  const fhirStore = await healthcare.projects.locations.datasets.fhirStores.setIamPolicy(
    request
  );
  console.log(
    'Set FHIR store IAM policy:',
    JSON.stringify(fhirStore.data, null, 2)
  );
};

setFhirStoreIamPolicy();

Python

def set_fhir_store_iam_policy(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        fhir_store_id,
        member,
        role,
        etag=None):
    """Sets the IAM policy for the specified FHIR store.

        A single member will be assigned a single role. A member can be any of:

        - allUsers, that is, anyone
        - allAuthenticatedUsers, anyone authenticated with a Google account
        - user:email, as in 'user:somebody@example.com'
        - group:email, as in 'group:admins@example.com'
        - domain:domainname, as in 'domain:example.com'
        - serviceAccount:email,
            as in 'serviceAccount:my-other-app@appspot.gserviceaccount.com'

        A role can be any IAM role, such as 'roles/viewer', 'roles/owner',
        or 'roles/editor'
    """
    client = get_client(service_account_json)
    fhir_store_parent = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)
    fhir_store_name = '{}/fhirStores/{}'.format(
        fhir_store_parent, fhir_store_id)

    policy = {
        "bindings": [
            {
              "role": role,
              "members": [
                member
              ]
            }
        ]
    }

    if etag is not None:
        policy['etag'] = etag

    request = client.projects().locations().datasets().fhirStores(
        ).setIamPolicy(resource=fhir_store_name, body={'policy': policy})
    response = request.execute()

    print('etag: {}'.format(response.get('name')))
    print('bindings: {}'.format(response.get('bindings')))
    return response

curl command

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.fhirResourceReader binding:

{
  "role":"roles/healthcare.fhirResourceReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, call projects.locations.datasets.fhirStores.setIamPolicy to make the updates.

To set a FHIR store-level Cloud IAM policy, make a POST request and provide the name of the dataset, the name of the FHIR store, the policy, and an access token. The following sample shows a POST request using curl to grant a new user the existing roles/healthcare.fhirResourceReader role.

The policy can be written directly in the request, as shown here, or it can be passed in as a JSON or YAML file. For examples of how to format a policy as JSON or YAML, see Policy.
curl -X POST \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.fhirStoreAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.fhirResourceReader',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID:setIamPolicy"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

PowerShell

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.fhirResourceReader binding:

{
  "role":"roles/healthcare.fhirResourceReader",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, call projects.locations.datasets.fhirStores.setIamPolicy to make the updates.

To set a FHIR store-level Cloud IAM policy, make a POST request and provide the name of the dataset, the name of the FHIR store, the policy, and an access token. The following sample shows a POST request using Windows PowerShell to grant a new user the existing roles/healthcare.fhirResourceReader role.

The policy can be written directly in the request, as shown here, or it can be passed in as a JSON or YAML file. For examples of how to format a policy as JSON or YAML, see Policy.
$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.fhirStoreAdmin',
          'members': [
            'user:user-1@example.com',
          ]
        },
        {
          'role': 'roles/healthcare.fhirResourceReader',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/fhirStores/FHIR_STORE_ID:setIamPolicy" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.fhirStoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.fhirResourceViewer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

Using Cloud Identity and Access Management with HL7v2 stores

The following sections show how to get, modify, and set a policy for an HL7v2 store. These sections use the following example policy as a starting point:

{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Getting a policy

The following samples show how to read an HL7v2 store-level Cloud IAM policy. For more information, see projects.locations.datasets.hl7V2Stores.getIamPolicy.

Console

To view the Cloud IAM policy for an HL7v2 store:

  1. In the GCP Console, go to the Datasets page.

    Go to the Datasets page

  2. Click the ID of the dataset that contains the HL7v2 store and then select the HL7v2 store that you want to get a policy for.
  3. Click Show info panel.
  4. To view the members assigned to a role, expand the role.

GCLOUD COMMAND

To view the Cloud IAM policy for an HL7v2 store, run the hl7v2-stores get-iam-policy command. Specify the HL7v2 store name, the dataset name, and the location.

gcloud beta healthcare hl7v2-stores get-iam-policy HL7V2_STORE_ID \
    --dataset=DATASET_ID \
    --location=REGION 

If the request is successful, the bindings are displayed.

bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.hl7v2StoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  role: roles/healthcare.hl7v2Consumer
etag: bytes
version: VERSION_NUMBER

curl command

To read the Cloud IAM policy for an HL7v2 store, make a GET request and provide the name of the dataset, the name of the HL7v2 store, and an access token. The following sample shows a GET request using curl.

curl -X GET \
     -H "Authorization: Bearer "$(gcloud auth print-access-token) \
     "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID:getIamPolicy"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

PowerShell

To read the Cloud IAM policy for an HL7v2 store, make a GET request and provide the name of the dataset, the name of the HL7v2 store, and an access token. The following sample shows a GET request using Windows PowerShell.

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Get `
  -Headers $headers `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID:getIamPolicy" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com"
      ]
    }
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// hl7V2IAMPolicy gets the IAM policy.
func hl7V2IAMPolicy(w io.Writer, projectID, location, datasetID, hl7V2StoreID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	storesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7v2Stores/%s", projectID, location, datasetID, hl7V2StoreID)

	policy, err := storesService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)
	}

	fmt.Fprintf(w, "IAM policy etag: %q\n", policy.Etag)
	return nil
}

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Policy;
import java.io.IOException;
import java.util.Collections;

public class Hl7v2StoreGetIamPolicy {
  private static final String DATASET_NAME = "projects/%s/locations/%s/datasets/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2StoreGetIamPolicy(String hl7v2StoreName) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Create request and configure any parameters.
    Hl7V2Stores.GetIamPolicy request =
        client.projects().locations().datasets().hl7V2Stores().getIamPolicy(hl7v2StoreName);

    // Execute the request and process the results.
    Policy policy = request.execute();
    System.out.println("HL7v2 store IAMPolicy retrieved: \n" + policy.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1beta1');

const getHl7v2StoreIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const hl7v2StoreId = 'my-hl7v2-store';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {resource_};

  const hl7v2Store = await healthcare.projects.locations.datasets.hl7V2Stores.getIamPolicy(
    request
  );
  console.log(
    'Got HL7v2 store IAM policy:',
    JSON.stringify(hl7v2Store.data, null, 2)
  );
};

getHl7v2StoreIamPolicy();

Python

def get_hl7v2_store_iam_policy(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        hl7v2_store_id):
    """Gets the IAM policy for the specified hl7v2 store."""
    client = get_client(service_account_json)
    hl7v2_store_parent = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)
    hl7v2_store_name = '{}/hl7V2Stores/{}'.format(
        hl7v2_store_parent, hl7v2_store_id)

    request = client.projects().locations().datasets().hl7V2Stores(
        ).getIamPolicy(resource=hl7v2_store_name)
    response = request.execute()

    print('etag: {}'.format(response.get('name')))
    return response

Modifying a policy

The following samples grant a new user the roles/healthcare.hl7V2Consumer role. For more information, see projects.locations.datasets.hl7V2Stores.setIamPolicy.

Console

To set an HL7v2 store-level Cloud IAM policy:

  1. In the GCP Console, go to the Datasets page.

    Go to the Datasets page

  2. Click the ID of the dataset that contains the HL7v2 store and then select the HL7v2 store that you want to set a policy for.
  3. Click Show info panel.
  4. Click Add member.
  5. In the New members field, enter one or more identities that need access to the HL7v2 store.
  6. In the Select a role list, under Cloud Healthcare, select the permission that you want to grant. For example, Healthcare HL7v2 Message Consumer.
  7. Click Save.

GCLOUD COMMAND

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.hl7V2Consumer binding:

{
  "role":"roles/healthcare.hl7V2Consumer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, run the appropriate set-iam-policy command to make the changes. To set an HL7v2 store-level policy, run the gcloud beta healthcare hl7v2-stores set-iam-policy command. Specify the HL7v2 store name, the dataset name, the location, and the path to the policy file that you created.

gcloud beta healthcare hl7v2-stores set-iam-policy HL7V2_STORE_ID \
    --dataset=DATASET_ID \
    --location=REGION \
    POLICY_FILE_NAME 

If the request is successful, the HL7v2 store name and the bindings are displayed.

Updated IAM policy for hl7v2Store [HL7V2_STORE_ID].
bindings:
- members:
  - user:user-1@example.com
  role: roles/healthcare.hl7v2StoreAdmin
  - serviceAccount:service-account-13@appspot.gserviceaccount.com
  - user:user-2@example.com
  - user:NEW_USER_EMAIL_ADDRESS
  role: roles/healthcare.hl7v2Consumer
etag: bytes
version: VERSION_NUMBER

curl command

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.hl7V2Consumer binding:

{
  "role":"roles/healthcare.hl7V2Consumer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, call projects.locations.datasets.hl7V2Stores.setIamPolicy to make the updates.

To set an HL7v2 store-level Cloud IAM policy, make a POST request and provide the name of the dataset, the name of the HL7v2 store, the policy, and an access token. The following sample shows a POST request using curl to grant a new user the existing roles/healthcare.hl7V2Consumer role.

The policy can be written directly in the request, as shown here, or it can be passed in as a JSON or YAML file. For examples of how to format a policy as JSON or YAML, see Policy.
curl -X POST \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    -H "Content-Type: application/json; charset=utf-8" \
    --data "{
      'policy': {
        'bindings': [
          {
            'role':'roles/healthcare.hl7V2StoreAdmin',
            'members': [
              'user:user-1@example.com'
            ]
          },
          {
            'role':'roles/healthcare.hl7V2Consumer',
            'members': [
              'serviceAccount:service-account-13@appspot.gserviceaccount.com',
              'user:user-2@example.com',
              'user:NEW_USER_EMAIL_ADDRESS'
            ]
          }
        ]
      }
    }" "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID:setIamPolicy"

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

PowerShell

Grant or revoke roles to users by modifying the policy that you retrieved, programmatically or using a text editor. The etag value changes when the policy changes, so you must specify the current value.

To grant a new user the role, append their email address to the members array under the roles/healthcare.hl7V2Consumer binding:

{
  "role":"roles/healthcare.hl7V2Consumer",
  "members": [
    "serviceAccount:service-account-13@appspot.gserviceaccount.com",
    "user:user-2@example.com",
    "user:NEW_USER_EMAIL_ADDRESS"
  ]
}
To revoke a member's access, delete their email address from the members array. To revoke access for the last member of a role, delete the bindings array for the role. You cannot have a bindings array in your policy with no members.

Setting a policy

After you have modified the policy to grant the applicable roles, call projects.locations.datasets.hl7V2Stores.setIamPolicy to make the updates.

To set an HL7v2 store-level Cloud IAM policy, make a POST request and provide the name of the dataset, the name of the HL7v2 store, the policy, and an access token. The following sample shows a POST request using curl to grant a new user the existing roles/healthcare.hl7V2Consumer role.

The policy can be written directly in the request, as shown here, or it can be passed in as a JSON or YAML file. For examples of how to format a policy as JSON or YAML, see Policy.
$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Invoke-WebRequest `
  -Method Post `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body "{
    'policy': {
      'bindings': [
        {
          'role': 'roles/healthcare.hl7V2StoreAdmin',
          'members': [
            'user:user-1@example.com',
          ]
        },
        {
          'role': 'roles/healthcare.hl7V2Consumer',
          'members': [
            'serviceAccount:service-account-13@appspot.gserviceaccount.com',
            'user:user-2@example.com',
            'user:NEW_USER_EMAIL_ADDRESS'
          ]
        }
      ]
    }
  }" `
  -Uri "https://healthcare.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/datasets/DATASET_ID/hl7V2Stores/HL7V2_STORE_ID:setIamPolicy" | Select-Object -Expand Content

If the request is successful, the server returns a 200 OK HTTP status code and the response in JSON format:

200 OK
{
  "etag":"bytes",
  "bindings": [
    {
      "role":"roles/healthcare.hl7V2StoreAdmin",
      "members": [
        "user:user-1@example.com"
      ]
    },
    {
      "role":"roles/healthcare.hl7V2Consumer",
      "members": [
        "serviceAccount:service-account-13@appspot.gserviceaccount.com",
        "user:user-2@example.com",
        "user:NEW_USER_EMAIL_ADDRESS"
      ]
    }
  ]
}

Go

import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1beta1"
)

// setHL7V2IAMPolicy sets an IAM policy.
func setHL7V2IAMPolicy(w io.Writer, projectID, location, datasetID, hl7V2StoreID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	storesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores

	name := fmt.Sprintf("projects/%s/locations/%s/datasets/%s/hl7v2Stores/%s", projectID, location, datasetID, hl7V2StoreID)

	policy, err := storesService.GetIamPolicy(name).Do()
	if err != nil {
		return fmt.Errorf("GetIamPolicy: %v", err)
	}

	policy.Bindings = append(policy.Bindings, &healthcare.Binding{
		Members: []string{"user:example@example.com"},
		Role:    "roles/viewer",
	})

	req := &healthcare.SetIamPolicyRequest{
		Policy: policy,
	}

	policy, err = storesService.SetIamPolicy(name, req).Do()
	if err != nil {
		return fmt.Errorf("SetIamPolicy: %v", err)
	}

	fmt.Fprintf(w, "Sucessfully set IAM Policy.\n")
	return nil
}

Java


import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare;
import com.google.api.services.healthcare.v1beta1.CloudHealthcare.Projects.Locations.Datasets.Hl7V2Stores;
import com.google.api.services.healthcare.v1beta1.CloudHealthcareScopes;
import com.google.api.services.healthcare.v1beta1.model.Binding;
import com.google.api.services.healthcare.v1beta1.model.Policy;
import com.google.api.services.healthcare.v1beta1.model.SetIamPolicyRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class Hl7v2StoreSetIamPolicy {
  private static final String HL7v2_NAME = "projects/%s/locations/%s/datasets/%s/hl7V2Stores/%s";
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();
  private static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  public static void hl7v2StoreSetIamPolicy(String hl7v2StoreName) throws IOException {
    // String hl7v2StoreName =
    //    String.format(
    //        HL7v2_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-hl7v2-id");

    // Initialize the client, which will be used to interact with the service.
    CloudHealthcare client = createClient();

    // Configure the IAMPolicy to apply to the store.
    // For more information on understanding IAM roles, see the following:
    // https://cloud.google.com/iam/docs/understanding-roles
    Binding binding =
        new Binding()
            .setRole("roles/healthcare.hl7V2Consumer")
            .setMembers(Arrays.asList("domain:google.com"));
    Policy policy = new Policy().setBindings(Arrays.asList(binding));
    SetIamPolicyRequest policyRequest = new SetIamPolicyRequest().setPolicy(policy);

    // Create request and configure any parameters.
    Hl7V2Stores.SetIamPolicy request =
        client
            .projects()
            .locations()
            .datasets()
            .hl7V2Stores()
            .setIamPolicy(hl7v2StoreName, policyRequest);

    // Execute the request and process the results.
    Policy updatedPolicy = request.execute();
    System.out.println("HL7v2 policy has been updated: " + updatedPolicy.toPrettyString());
  }

  private static CloudHealthcare createClient() throws IOException {
    // Use Application Default Credentials (ADC) to authenticate the requests
    // For more information see https://cloud.google.com/docs/authentication/production
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(HTTP_TRANSPORT, JSON_FACTORY)
            .createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));

    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        request -> {
          credential.initialize(request);
          request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
          request.setConnectTimeout(60000); // 1 minute connect timeout
          request.setReadTimeout(60000); // 1 minute read timeout
        };

    // Build the client for interacting with the service.
    return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
        .setApplicationName("your-application-name")
        .build();
  }
}

Node.js

const {google} = require('googleapis');
const healthcare = google.healthcare('v1beta1');

const setHl7v2StoreIamPolicy = async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform'],
  });
  google.options({auth});

  // TODO(developer): uncomment these lines before running the sample
  // const cloudRegion = 'us-central1';
  // const projectId = 'adjective-noun-123';
  // const datasetId = 'my-dataset';
  // const member = 'user:example@gmail.com';
  // const role = 'roles/healthcare.hl7V2StoreViewer';
  const resource_ = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/hl7V2Stores/${hl7v2StoreId}`;
  const request = {
    resource_,
    resource: {
      policy: {
        bindings: [
          {
            members: member,
            role: role,
          },
        ],
      },
    },
  };

  const hl7v2Store = await healthcare.projects.locations.datasets.hl7V2Stores.setIamPolicy(
    request
  );
  console.log(
    'Set HL7v2 store IAM policy:',
    JSON.stringify(hl7v2Store.data, null, 2)
  );
};

setHl7v2StoreIamPolicy();

Python

def set_hl7v2_store_iam_policy(
        service_account_json,
        project_id,
        cloud_region,
        dataset_id,
        hl7v2_store_id,
        member,
        role,
        etag=None):
    """Sets the IAM policy for the specified hl7v2 store.

        A single member will be assigned a single role. A member can be any of:

        - allUsers, that is, anyone
        - allAuthenticatedUsers, anyone authenticated with a Google account
        - user:email, as in 'user:somebody@example.com'
        - group:email, as in 'group:admins@example.com'
        - domain:domainname, as in 'domain:example.com'
        - serviceAccount:email,
            as in 'serviceAccount:my-other-app@appspot.gserviceaccount.com'

        A role can be any IAM role, such as 'roles/viewer', 'roles/owner',
        or 'roles/editor'
    """
    client = get_client(service_account_json)
    hl7v2_store_parent = 'projects/{}/locations/{}/datasets/{}'.format(
        project_id, cloud_region, dataset_id)
    hl7v2_store_name = '{}/hl7V2Stores/{}'.format(
        hl7v2_store_parent, hl7v2_store_id)

    policy = {
        "bindings": [
            {
              "role": role,
              "members": [
                member
              ]
            }
        ]
    }

    if etag is not None:
        policy['etag'] = etag

    request = client.projects().locations().datasets().hl7V2Stores(
        ).setIamPolicy(resource=hl7v2_store_name, body={'policy': policy})
    response = request.execute()

    print('etag: {}'.format(response.get('name')))
    print('bindings: {}'.format(response.get('bindings')))
    return response

What's next

¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...

Cloud Healthcare API