Skip to main content

Test IAM permissions

This page describes how to programmatically test IAM permissions against an Identity and Access Management API resource. This is especially useful to check whether the currently authenticated identity is allowed to perform a specific action. Testing permissions is also used in Permission-Aware UIs to hide action items from the user interface, e.g. if a user is not allowed to delete a resource the delete button won't be rendered in the UI.

Permissions

The list of permissions that can be tested against Identity and Access Management API resources can be found in the reference page for IAM permissions.

Sample

The following code sample shows how to test a set of permissions against a service account.

Replace [SERVICE-ACCOUNT] with the resource name of the service account that the permissions should be tested against, e.g. users/123/serviceAccounts/my-service-account.

tip

Tip: do not forget to replace CLIENT-ID and CLIENT-SECRET with valid IAM Service Account client credentials.

package main

import (
"context"
"log"

"golang.org/x/oauth2/clientcredentials"

"google.golang.org/api/option"
"google.golang.org/genproto/googleapis/iam/v1"

gapic "github.com/animeapis/api-go-client/iam/admin/v1alpha1"
)

var (
ServiceAccount = "[SERVICE-ACCOUNT]"

TestPermissions = []string{
"iam.serviceAccounts.get",
"iam.serviceAccounts.create",
"iam.serviceAccounts.setIamPolicy",
}

ClientID = "[CLIENT-ID]"
ClientSecret = "[CLIENT-SECRET]"
)

var (
TokenURL = "https://accounts.animeshon.com/o/oauth2/token"
Endpoint = "iam.animeapis.com:443"
)

func main() {
ctx := context.Background()

config := &clientcredentials.Config{
ClientID: ClientID,
ClientSecret: ClientSecret,
TokenURL: TokenURL,
}

options := []option.ClientOption{
option.WithEndpoint(Endpoint),
option.WithTokenSource(config.TokenSource(ctx)),
}

client, err := gapic.NewIamClient(ctx, options...)
if err != nil {
log.Fatalf("NewIamClient: %s", err)
}

request := &iam.TestIamPermissionsRequest{
Resource: ServiceAccount,
Permissions: TestPermissions,
}

response, err := client.TestIamPermissions(ctx, request)
if err != nil {
log.Fatalf("TestIamPermissions: %s", err)
}

log.Printf("resource : %s", ServiceAccount)
log.Printf("allowed permissions: %v", response.GetPermissions())
}
View on GitHub