You can configure policies for a bucket to grant permissions to other users to access specified Object Storage Service (OSS) resources.

Background information

  • The owner of a bucket can configure bucket policies for the bucket in the OSS console by using the GUI or by specifying policy syntax. Before you configure bucket policies by specifying policy syntax, you must understand the Action, Resource, and Condition fields in bucket policies. For more information, see Overview.
  • If you select 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 for the bucket owner. If you select Anonymous Accounts (*) for the Accounts parameter and configure the Conditions parameter when you configure a bucket policy, the bucket policy applies to all users, including the bucket owner.
  • You can configure multiple bucket policies for a bucket. The total size of the policies cannot exceed 16 KB.

Scenarios

Bucket policies can be used for access authorization in the following scenarios:

  • You need to grant permissions to another Alibaba Cloud account or anonymous users to access or manage all or specified resources in a bucket.
  • You need to 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. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket for which you want to configure bucket policies.
  3. In the left-side navigation pane, choose Files > Files. On the page that appears, click Authorize.

    You can also choose Access Control > Bucket Policy in the left-side navigation pane, and then click Configure in the Bucket Policy section.

  4. On the GUI tab, click Authorize.
  5. In the Authorize panel, configure the parameters and then 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 specified 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 name of the directory. For example, to grant users the permissions 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 that excludes 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.
    • Anonymous Accounts (*): Select this option if you want to grant all users the permissions to access the specified resources.
    • RAM Users: 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.
      Notice 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 RAM user list of the current Alibaba Cloud account. For more information about how to grant the ListUsers permission to a RAM user, see Grant permissions to a RAM user.
    • Other Accounts: Select this option if you want to grant other Alibaba Cloud accounts, RAM users, or temporary users generated by 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 UIDs of the Alibaba Cloud accounts or RAM users.
      • To grant temporary users generated by STS the permissions to access the specified resources, enter the user and role information 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 assumes 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 a temporary credential provided by STS to access OSS.
      Notice If you grant a temporary user generated by STS the permissions to access your OSS resources, the temporary user cannot use the OSS console to access your OSS resources. However, the user can use ossutil, OSS API operations, or OSS SDKs to access your OSS resources.
    Authorized Operation You can use 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 requirements. You can move the pointer over the mark icon on 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.
      Notice
      • 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 the permissions configured in the policies. However, the policy in which the Authorized Operation parameter is set to None takes precedence. For example, if you configure a first policy to grant the Read-Only permission to a user and configure a second policy to grant the Read/Write permission to the same user, the permission of the user is Read/Write. If you configure a third 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 actions that are supported by OSS, see Overview.
    Conditions Optional. You can configure this parameter in both 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 both 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 to force all requests to 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 account or another account in the field below. For more information about how to create a VPC, see Create a VPC and a vSwitch.
  6. In the message that appears, click OK.

Method 2: Configure bucket policies by specifying policy syntax

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket for which you want to configure bucket policies.
  3. In the left-side navigation pane, choose Files > Files. On the page that appears, click Authorize.
  4. On the Syntax tab, click Edit.

    You can specify policy syntax based on your business requirements for fine-grained access control. The following examples describe the bucket policies configured by the resource owner whose UID is 174649585760xxxx in different scenarios:

    • Example 1: Allow anonymous 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: Forbid anonymous users whose IP addresses are not in the CIDR block 192.168.0.0/16 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"
      }
  5. 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 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 the endpoint based on your business requirements. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS, because the account has permissions on all API operations. 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 {
            // Specify policyText. 
            String policyText = "{\"Statement\": [{\"Effect\": \"Allow\", \"Action\": [\"oss:GetObject\", \"oss:ListObjects\"], \"Resource\": [\"acs:oss:*:*:*/user1/*\"]}], \"Version\": \"1\"}";

            // Configure the 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;

// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";

$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:*:*:*/user1/*"]
  }
  ]
}
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({
  bucket: '<Your BucketName>',
  // This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint based on your requirements.
  region: '<Your Region>',
  // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS, because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create your RAM user, log on to https://ram.console.aliyun.com.
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>',
});

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

async function putPolicy() {
  const result = await client.putBucketPolicy('<Your Bucket Name>', policy);
  console.log(result)
}

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

import oss2
import json

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. 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. 
# Specify yourBucketName as the name of the bucket. 
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')

# Configure the value of policy_text, which is the content of the bucket policy. 
policy_text = '{"Statement": [{"Effect": "Allow", "Action": ["oss:GetObject", "oss:ListObjects"], "Resource": ["acs:oss:*:*:*/user1/*"]}], "Version": "1"}'

# Configure the bucket policy. 
bucket.put_bucket_policy(policy_text)
using Aliyun.OSS;
using Aliyun.OSS.Common;
var endpoint = "<yourEndpoint>";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create your RAM user, log on to the RAM console.
String accessKeyId = "<yourAccessKeyId>";
var accessKeyId = "<yourAccessKeyId>";
var accessKeySecret = "<yourAccessKeySecret>";
var bucketName = "<yourBucketName>";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Configure a 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 Object Storage Service (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 an authorization policy. 
    policyConfig := `
    {
        "Statement": [
            {
                "Action": [
                    "oss:GetObject",
                    "oss:ListObjects"
                ],
                "Effect" : "Allow",
                "Resource" : ["acs:oss:*:*:*/user1/*"]
            }
        ],
        "Version": "1"
    }`

    // Set yourBucketName to the name of your bucket and then specify the configured policy for 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 a bucket policy. For example, you can allow users to list or download objects whose names are prefixed with user1/ in the bucket. */
    std::string policy = 
        R"(
        {
            "Statement": [
            {
                "Action": [
                    "oss:GetObject",
                    "oss:ListObjects"
                ],
                    "Effect" : "Allow",
                        "Resource" : ["acs:oss:*:*:*/user1/*"]
            }
            ],
                "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 information about how to use ossutil to configure or modify bucket policies, see bucket-policy.

Use the RESTful API

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 the following methods to access the resources specified in the bucket policy:

  • Object URL (only for authorized anonymous users)

    Anonymous users can 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 next to My OSS Paths. In the Add Path panel, add the bucket name and the object path specified in the bucket policy. For more information, see Set OSS 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