Assign IAM policies
This page describes how to programmatically grant access to an Image API resource.
Examples of use cases where assigning IAM policies is necessary include:
- Allowing a third-party application to upload images to an album.
- Allowing other users to manage images available in an album.
- Allowing anyone to view images uploaded to a public album.
Roles
The list of roles that can be assigned to Image API resources can be found in the reference page for IAM roles.
danger
The image.settingsAdmin
role is internally managed and cannot be assigned by anyone except administrators.
IAM Members
The IAM members that can be assigned to an IAM policy binding can be one of the following:
Member | Description |
---|---|
allUsers | Used to grant roles to anyone, both authenticated and unauthenticated. |
user:12345567890 | Used to grant roles only to a specific user. |
serviceAccount:12345567890 | Used to grant roles only to a specific service account. |
Sample
The following code sample shows how to set an album IAM policy with the role roles/image.viewer
assigned to allUsers
. This means that any user, doesn't matter if authenticated or not, will be able to access all images in the specified album.
Replace [ALBUM]
with the resource name of the album that the policy should be assigned to, e.g. users/123/albums/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.
- Golang
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/image/v1alpha1"
)
var (
Album = "[ALBUM]"
Role = "roles/image.viewer"
Member = "allUsers"
ClientID = "[CLIENT-ID]"
ClientSecret = "[CLIENT-SECRET]"
)
var (
TokenURL = "https://accounts.animeshon.com/o/oauth2/token"
Endpoint = "image.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.NewClient(ctx, options...)
if err != nil {
log.Fatalf("NewClient: %s", err)
}
request := &iam.SetIamPolicyRequest{
Resource: Album,
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", Album)
log.Printf("bindings: %v", policy.Bindings)
}