All Products
Search
Document Center

Object Storage Service:Overview

Last Updated:Jun 05, 2023

You can configure a bucket policy to authorize other users to access specific Storage Service (OSS) resources in a bucket.

Usage notes

  • The owner of a bucket can use the GUI or specify policy syntax to configure bucket policies for the bucket in the OSS console. Before you specify policy syntax to configure bucket policies, you must understand the Action, Resource, and Condition elements in bucket policies. For more information, see Overview.

  • If you select All Accounts (*) that includes anonymous accounts for the Accounts parameter and do not configure the Conditions parameter when you configure a bucket policy, the bucket policy applies to all users except the bucket owner. If you select All Accounts (*) that includes anonymous accounts for the Accounts parameter and configure the Conditions parameter when you configure a bucket policy, the bucket policy takes effect for all users, including the bucket owner.

  • You can configure multiple bucket policies for a bucket. The total size of the bucket policies cannot exceed 16 KB.

Scenarios

Bucket policies can be used to grant access permissions to users in the following scenarios:

  • You must grant permissions to another Alibaba Cloud account or specific users to access or manage resources in a bucket.

  • You must grant different permissions such as read-only, read and write, or full access to RAM users that belong to the same Alibaba Cloud account to allow the users to access or manage resources in your bucket.

Use the OSS console

Method 1: Configure bucket policies by using the GUI

  1. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  2. In the left-side navigation tree, choose Permission Control > Bucket Policy .

  3. On the Bucket Policy tab, click Add in GUI and click Authorize.

  4. In the Authorize panel, configure the parameters and click OK. The following table describes the parameters.

    Parameter

    Description

    Applied To

    Select the resources on which you want to grant other users the access permissions.

    • Whole Bucket: The bucket policy applies to all resources in the bucket.

    • Specified Resource: The bucket policy applies only to specific resources in the bucket. You can configure multiple bucket policies for specific resources in a bucket.

      • Configure a bucket policy for a directory

        To configure a bucket policy to grant users the permissions to access all subdirectories and objects in a directory, add an asterisk (*) after the directory name. For example, to authorize users to access all subdirectories and objects in a directory named abc, enter abc/*.

      • Configure a bucket policy for a specific object

        To configure a bucket policy to grant users the permissions to access a specific object, enter the full path of the object excluding the bucket name. For example, to grant users the permissions to access an object named myphoto.png in the abc directory, enter abc/myphoto.png.

    Accounts

    Select the type of accounts to which you want to grant the permissions.

    • All Accounts (*): Select this option if you want to grant all users the permissions to access the specified resources.

    • RAM User: Select this option if you want to grant the RAM users of the current Alibaba Cloud account the permissions to access the specified resources. You can select individual RAM users from the drop-down list. If you want to grant the permissions to multiple RAM users, we recommend that you enter the keyword of the RAM usernames in the search box to perform fuzzy match.

      Important

      If you select this option, you must log on to the OSS console by using an Alibaba Cloud account or a RAM user that has the management permissions on the bucket and the ListUsers permission in the RAM console. If you do not use an Alibaba Cloud account or a RAM user that has the required permissions, you cannot view the list of RAM users of the current Alibaba Cloud account. For more information about how to grant the ListUsers permission to RAM users, see Grant permissions to the RAM user.

    • Other Accounts: Select this option if you want to grant other Alibaba Cloud accounts, RAM users, or temporary users generated based on Security Token Service (STS) the permissions to access the specified resources.

      • To grant other Alibaba Cloud accounts or RAM users the permissions to access the specified resources, enter the unique identifiers (UIDs) of the Alibaba Cloud accounts or RAM users.

      • To grant temporary users generated based on STS the permissions to access the specified resources, enter the value in the following format: arn:sts::{RoleOwnerUid}:assumed-role/{RoleName}/{RoleSessionName}. For example, the role used to generate a temporary user is testrole, the UID of the Alibaba Cloud account that owns the role is 12345, and the RoleSessionName that is specified when the temporary user is generated is testsession. In this case, enter arn:sts::12345:assumed-role/testrole/testsession. To grant all temporary users the permissions to access the specified resources, use asterisks (*) as wildcard characters. For example, enter arn:sts::*:*/*/*. For more information about how to generate a temporary user, see Use temporary credentials provided by STS to access OSS.

      Important

      If you grant a temporary user generated based on STS the permissions to access your OSS resources, the temporary user cannot access your OSS resources in the OSS console. However, the temporary user can use ossutil, API operations, or OSS SDKs to access your OSS resources.

    Authorized Operation

    You can use one of the following methods to specify authorized operations: Basic Settings and Advanced Settings.

    • Basic Settings

      If you select this option, you can configure the following permissions based on your business requirements. You can move the pointer over the mark icon to the right side of each permission to view the actions that correspond to the permission.

      • Read-Only (excluding ListObject): allows authorized users to view and download the specified resources.

      • Read-Only (including ListObject): allows authorized users to view, list, and download the specified resources.

      • Read/Write: allows authorized users to read data from and write data to the specified resources.

      • Any Operation: allows authorized users to perform all operations on the specified resources.

      • None: forbids authorized users from performing operations on the specified resources.

      Important
      • When you configure a policy for the bucket for which the OSS-HDFS service is enabled, you cannot set Authorized Operation to None. This helps ensure that users who use the OSS-HDFS service can access the .dlsdata/ directory in which OSS-HDFS data is stored and the objects in the directory.

      • If multiple bucket policies are configured for a user, the user has all permissions configured in the bucket policies. However, the bucket policy in which the Authorized Operation parameter is set to None takes precedence. For example, if you configure a first bucket policy to grant the Read-Only permission to a user and configure a second bucket policy to grant the Read/Write permission to the user, the permission of the user is Read/Write. If you configure a third bucket policy to grant the None permission to the user, the permission of the user is None.

      • The authorization effect for Read-Only (excluding ListObject), Read-Only (including ListObject), Read/Write, and Any Operation is Allow, and the authorization effect for None is Deny.

    • Advanced Settings

      If you select this option, you must configure the following parameters:

      • Effect: Select Allow or Deny.

      • Action: Specify the action that you want to allow or deny. You can specify an action that is supported by OSS. For more information about the types of actions, see Overview.

    Conditions

    Optional. You can configure this parameter in Basic Settings and Advanced Settings to specify the conditions that users must meet before the users can access OSS resources.

    • Access Method: By default, authorized users can access OSS resources over HTTP and HTTPS. If you want the authorized users to access the specified resources in the bucket over HTTPS, select HTTPS. If you want the authorized users to access the specified resources in the bucket over HTTP, select HTTP. Compared with HTTP, HTTPS is more secure.

      If you want all requests to forcibly access resources in the bucket by using one protocol, such as HTTPS, you must specify the syntax of the bucket policy. For more information, see How do I configure an HTTPS request and an SSL certificate?

    • IP =: Specify the IP addresses or CIDR blocks that can be used to access OSS resources. Separate multiple IP addresses with commas (,).

    • IP ≠: Specify the IP addresses or CIDR blocks that cannot be used to access OSS resources. Separate multiple IP addresses with commas (,).

    • VPC: Select the ID of the Apsara Stack VPC that belongs to the current Alibaba Cloud account from the drop-down list. You can also enter the ID of the VPC created by using the current Alibaba Cloud account or another account in the field. For information about how to create a VPC, see Create and manage a VPC.

  5. Click OK.

Method 2: Configure bucket policies by specifying policy syntax

  1. In the left-side navigation tree, choose Permission Control > Bucket Policy.

  2. On the Bucket Policy tab, click Add in GUI and click Edit.

  3. In the policy field, enter the bucket policy.

    To achieve fine-grained access control, you can specify policy syntax based on your business requirements. The following sample code provides examples on how the resource owner whose UID is 174649585760xxxx configures bucket policies in various scenarios:

    • Example 1: Allow all users to list all objects in a bucket named examplebucket.

      {
          "Statement": [
              {
                  "Action": [
                      "oss:ListObjects",
                      "oss:ListObjectVersions"
      
                  ],
                  "Effect": "Allow",            
                  "Principal": [
                      "*"
                  ],            
                  "Resource": [
                      "acs:oss:*:174649585760xxxx:examplebucket"
                  ]
              },
      
          ],
          "Version": "1"
      }
    • Example 2: Deny all users whose IP addresses are not in the 192.168.0.0/16 CIDR block from managing a bucket named examplebucket.

      {
          "Version": "1",
          "Statement": [
              {
                  "Effect": "Deny",
                  "Action": "oss:*",
                  
                  "Principal": [
                      "*"
                  ],            
                  "Resource": [
                      "acs:oss:*:174649585760xxxx:examplebucket"
                  ],
                  "Condition":{
                      "NotIpAddress": {
                          "acs:SourceIp": ["192.168.0.0/16"]
                      }
                  }
              }
          ]
      }
    • Example 3: Allow a RAM user whose UID is 20214760404935xxxx only to read the hangzhou/2020 and hangzhou/2015 directories in a bucket named examplebucket.

      {
          "Statement": [
              {
                  "Action": [
                      "oss:GetObject",
                      "oss:GetObjectAcl",
                      "oss:GetObjectVersion",
                      "oss:GetObjectVersionAcl"
      
                  ],
                  "Effect": "Allow",             
                  "Principal": [
                      "20214760404935xxxx"
                  ],            
                  "Resource": [
                      "acs:oss:*:174649585760xxxx:examplebucket/hangzhou/2020/*",
                      "acs:oss:*:174649585760xxxx:examplebucket/hangzhou/2015/*"
                  ]
              },
              {
                  "Action": [
                      "oss:ListObjects",
                      "oss:ListObjectVersions"
                  ],
                  "Condition": {
                      "StringLike": {
                          "oss:Prefix": [
                              "hangzhou/2020/*",
                              "hangzhou/2015/*"
                          ]
                      }
                  },
                  "Effect": "Allow",
                  "Principal": [
                      "20214760404935xxxx"
                  ],
                  "Resource": [
                      "acs:oss:*:174649585760xxxx:examplebucket"
                  ]
              }
          ],
          "Version": "1"
      }
  4. Click Save.

Use ossbrowser

You can use ossbrowser to perform the same bucket-level operations that you can perform in the OSS console. You can follow the on-screen instructions in ossbrowser to modify bucket policies. For more information about how to use ossbrowser, see Use ossbrowser.

Use OSS SDKs

The following sample code provides examples on how to configure bucket policies by using OSS SDKs for common programming languages. For more information about how to configure bucket policies by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            The following examples show how the bucket owner whose UID is 174649585760xxxx configures the bucket policy to grant the RAM user whose UID is 20214760404935xxxx permissions to list all objects in a bucket named examplebucket: 
            String policyText = "{\"Statement\": [{\"Effect\": \"Allow\", \"Action\": [\"oss:GetObject\", \"oss:ListObjects\"], \"Principal\": [\"20214760404935xxxx\"], \"Resource\": [\"acs:oss:*:174649585760xxxx:examplebucket/*\"]}], \"Version\": \"1\"}";

            // Configure the bucket policy. 
            ossClient.setBucketPolicy(bucketName, policyText);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);

// Specify the bucket policy. 
$policy = <<< BBBB
{
  "Version":"1",
  "Statement":[
  {
    "Action":[
    "oss:PutObject",
    "oss:GetObject"
  ],
    "Effect":"Allow",
    "Resource":["acs:oss:*:174649585760xxxx:examplebucket/*"]
  }
  ]
}
BBBB;

try {
    // Configure the bucket policy. 
    $ossClient->putBucketPolicy($bucket, $policy);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}

print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss')

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the name of the bucket. 
  bucket: 'yourbucketname'
});

// Configure the bucket policy. 
const policy = {
  Version: '1',
  Statement: [
  {
      Action: ['oss:PutObject', 'oss:GetObject'],
      Effect: 'Deny',
      Principal: ['27737962156157xxxx'],
      Resource: ['acs:oss:*:174649585760xxxx:examplebucket']
    }
  ]
};

async function putPolicy() {
  const result = await client.putBucketPolicy('yourbucketname', policy);
  console.log(result)
}

putPolicy()
# -*- coding: utf-8 -*-

import oss2
import json

# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
# Set yourBucketName to the name of your bucket. 
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')

# Specify policy_text. 
policy_text = '{"Statement": [{"Effect": "Allow", "Action": ["oss:GetObject", "oss:ListObjects"], "Resource": ["acs:oss:*:174649585760xxxx:examplebucket/*"]}], "Version": "1"}'

# Configure the bucket policy. 
bucket.put_bucket_policy(policy_text)
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Configure the bucket policy. 
    string policy = "{\"Version\":\"1\",\"Statement\":[{\"Action\":[\"oss:PutObject\",\"oss:GetObject\"],\"Resource\": \"acs:oss:*:*:*\",\"Effect\": \"Deny\"}]}\n";
    var request = new SetBucketPolicyRequest(bucketName, policy);
    client.SetBucketPolicy(request);
    Console.WriteLine("Set bucket:{0} Policy succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
package main

import (
    "fmt"
    "os"

    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Configure a policy. 
    policyConfig := `
    {
        "Statement": [
            {
                "Action": [
                    "oss:GetObject",
                    "oss:ListObjects"
                ],
                "Effect" : "Allow",
                "Resource" : ["acs:oss:*:174649585760xxxx:examplebucket/*"]
            }
        ],
        "Version": "1"
    }`

    // Assign the policy to the bucket. 
    // Specify the name of the bucket. 
    err = client.SetBucketPolicy("yourBucketName", policyConfig)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    fmt.Println("SetBucketPolicy success")
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /* Configure the policy. */
    std::string policy = 
        R"(
        {
            "Statement": [
            {
                "Action": [
                    "oss:GetObject",
                    "oss:ListObjects"
                ],
                    "Effect" : "Allow",
                        "Resource" : ["acs:oss:*:174649585760xxxx:examplebucket/*"]
            }
            ],
                "Version": "1"
        }
        )";
    SetBucketPolicyRequest request(BucketName);
    request.setPolicy(policy);
    auto outcome = client.SetBucketPolicy(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "Set Bucket Policy fail" <<
            ",code:" << outcome.error().Code() <<
            ",message:" << outcome.error().Message() <<
            ",requestId:" << outcome.error().RequestId() << std::endl;
    }

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}

Use ossutil

For more information about how to use ossutil to configure or modify bucket policies, see bucket-policy.

Use RESTful APIs

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketPolicy.

Access authorized OSS resources

After you configure a bucket policy for a bucket, you can use one of the following methods to access the resources specified in the bucket policy:

  • Object URLs (only if all users are authorized to access the resources)

    Enter the URL of an object specified in the policy in a browser to access the object. The URL of the object consists of the default domain name of the bucket or a custom domain name mapped to the bucket and the path of the object. Example: http://mybucket.oss-cn-beijing.aliyuncs.com/file/myphoto.png For more information, see OSS domain names.

  • OSS console

    Log on to the OSS console. In the left-side navigation pane, click the + icon to the right of Favorite Paths. In the Add Favorite Paths dialog box, add the bucket and the object path specified in the bucket policy. For more information about specific operations, see OSS access paths.

  • ossutil

    Use the authorized account that is specified in the bucket policy to log on to ossutil to access the resources specified in the policy. For more information, see ossutil.

  • ossbrowser

    Use the authorized account that is specified in the bucket policy to log on to ossbrowser. Enter the path of the object specified in the policy in the Preset OSS Path field. For more information, see ossbrowser.

  • OSS SDK

    You can use OSS SDKs for the following programming languages to access the resources that are specified in the policy: Java, PHP, Node.js, Python, Browser.js, .NET, Android, Go, iOS, C++, and C.

References