Skip to main content

Assign IAM policies

This page describes how to programmatically grant access to a Library API resource.

Roles

The list of roles that can be assigned to Library API resources can be found in the reference page for IAM roles.

IAM Members

The IAM members that can be assigned to an IAM policy binding can be one of the following:

MemberDescription
allUsersUsed to grant roles to anyone, both authenticated and unauthenticated.
user:12345567890Used to grant roles only to a specific user.
serviceAccount:12345567890Used to grant roles only to a specific service account.

Sample

The following code sample shows how to assign a playlist IAM policy with the role roles/library.viewer assigned to allUsers. This means that any user, doesn't matter if authenticated or not, will be able to access the playlist.

Replace [PLAYLIST] with the resource name of the playlist that the policy should be assigned to, e.g. users/123/playlists/456.

tip

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

caution

The SetIamPolicy method will always replace (overwrite) any previously defined policy.

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]"
Member = "[MEMBER]"

Role = "roles/iam.serviceAccountAdmin"

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.SetIamPolicyRequest{
Resource: ServiceAccount,
Policy: &iam.Policy{
Version: 1,
Bindings: []*iam.Binding{
{
Role: Role,
Members: []string{Member},
},
},
},
}

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

log.Printf("resource: %s", ServiceAccount)
log.Printf("bindings: %v", policy.Bindings)
}
View on GitHub