All Products
Search
Document Center

Object Storage Service:How do I access a private image object within a specific period of time?

Last Updated:Nov 21, 2025

If you use Elastic Compute Service (ECS) to write web pages, you may need to use a private image object in a bucket. If you want to access the private image object within a specific period of time, you can use ossutil or Object Storage Service (OSS) SDKs to generate a signed URL that has a long validity period for the image object. To protect the image object against unauthorized access, you must also configure hotlink protection for the bucket in which the image object is stored.

Step 1: Generate a signed URL

For security reasons, the default validity period of URLs generated in the OSS console is 3,600 seconds and the maximum validity period is 32,400 seconds. To generate signed URLs that have a validity period of longer than 32,400 seconds, use ossutil or OSS SDKs.

The following sample code provides examples on how to generate a signed URL for an object named exampleobject.png in a bucket named examplebucket and specify that the signed URL is valid within 30 days.

Use ossutil 1.0

ossutil sign oss://examplebucket/exampleobject.png --timeout 2592000
Note

Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.

Use OSS SDKs

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import java.net.URL;
import java.util.Date;
import com.aliyun.oss.common.comm.SignVersion;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // We recommend that you do not save access credentials in the project code. Otherwise, access credentials may be leaked, which compromises the security of all resources in your account. In this example, access credentials are obtained from environment variables. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampleobject.png. Do not include the bucket name in the full path. 
        String objectName = "exampleobject.png";
       
        // Create an OSSClient instance. 
        // Call the shutdown method to release resources when the OSSClient is no longer in use. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare the use of the V4 signature algorithm.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements. 
            
            // Obtain the current system time in milliseconds. 
            long currentTimeMillis = System.currentTimeMillis();
            // Calculate the time after 30 days in seconds.
            long expirationSeconds = currentTimeMillis/ 1000 + 30 * 24 * 3600;
            // Convert the time after 30 days in seconds to milliseconds to construct the Date parameter.
            Date expiration = new Date(expirationSeconds * 1000);
            
            // Generate the signed URL that is used to access the object by using GET methods. Visitors can enter the URL in a browser to access the object before the URL expires. 
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
            System.out.println(url);
        } 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;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;

// Obtain access credentials from environment variables. 
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// 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. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. 
$object = "exampleobject.txt";
// Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements. 
$timeout = 2592000;
try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);

    // Generate a signed URL for the GetObject request. 
    $signedUrl = $ossClient->signUrl($bucket, $object, $timeout);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");

// You can use the signed URL in your code or enter the URL in the address bar of a browser to access the object. 
$request = new RequestCore($signedUrl);
// Set the default method that is used to access the signed URL to GET. 
$request->set_method('GET');
$request->add_header('Content-Type', '');
$request->send_request();
$res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
    print(__FUNCTION__ . ": OK" . "\n");
} else {
    print(__FUNCTION__ . ": FAILED" . "\n");
};                    
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import requests

# Obtain access credentials from environment variables. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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 the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
object_name = 'exampledir/exampleobject.txt'

# Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements. 
# By default, OSS identifies forward slashes (/) in the full path of an object as escape characters in the signing process. Therefore, the signed URL cannot be directly used. 
# Set the slash_safe parameter to True. This way, OSS does not identify the forward slashes (/) in the full path of the object as escape characters, and the signed URL can be directly used. 
url = bucket.sign_url('GET', object_name, 2592000, slash_safe=True)     
print('Signed URL: ', url)

# Use the signed URL to download the object to your local computer. 
# Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
# By default, if you specify the name of a local file, such as examplefile.txt, but do not specify the local path, the downloaded object is saved to the local path of the project to which the sample program belongs. 
result = bucket.get_object_with_url_to_file(url, 'D:\\localpath\\examplefile.txt')
package main

    import (
        "fmt"
        "os"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
    )

func main() {
    /// Obtain access credentials from environment variables. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // 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. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"
    // Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
    objectName := "exampledir/exampleobject.txt"
    // Download the object to the local path and store the object as a local file. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path. 
    // If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
    localDownloadedFilename := "D:\\localpath\\examplefile.txt"

    // Query the name of the bucket. 
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        HandleError(err)
    }

    // Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements. 
    signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 2592000)
    if err != nil {
        HandleError(err)
    }

    body, err := bucket.GetObjectWithURL(signedURL)
    if err != nil {
        HandleError(err)
    }
    // Read the content of the object. 
    data, err := ioutil.ReadAll(body)
    body.Close()
    data = data // Use the downloaded data. 

    // Use the signed URL to download the object and store the object as a local file. 
    err = bucket.GetObjectToFileWithURL(signedURL, localDownloadedFilename)
    if err != nil {
        HandleError(err)
    }
}                    
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 = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file to which you want to download the object. Example: D:\\localpath\\examplefile.txt. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path. 
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    var metadata = client.GetObjectMetadata(bucketName, objectName);
    var etag = metadata.ETag;
    // Create a request to generate a signed URL. 
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
      {
        // Specify the validity period of the signed URL. Unit: hours. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements. 
        Expiration = DateTime.Now.AddHours(720),
    };
    var uri = client.GeneratePresignedUri(req);
    // Use the signed URL to download the object. 
    OssObject ossObject = client.GetObject(uri);
    using (var file = File.Open(downloadFilename, FileMode.OpenOrCreate))
    {
        using (Stream stream = ossObject.Content)
        {
            int length;
            int bufLength = 4 * 1024;
            var buf = new byte[bufLength];
            do
            {
                length = requestStream.Read(buf, 0, bufLength);
                fs.Write(buf, 0, length);
            } while (length != 0);
        }
    }
    Console.WriteLine("Get object by signatrue succeeded. {0} ", uri.ToString());
}
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);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* 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";
    /* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */ 
    std::string GetobjectUrlName = "exampledir/exampleobject.txt";

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

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Specify the validity period of the signed URL. Unit: seconds. In this example, the validity period is set to 30 days. You can configure the validity period based on your business requirements. */
    std::time_t t = std::time(nullptr) + 2592000;
    /* Generate a signed URL. */
    auto genOutcome = client.GeneratePresignedUrl(BucketName, GetobjectUrlName, t, Http::Get);
    if (genOutcome.isSuccess()) {
        std::cout << "GeneratePresignedUrl success, Gen url:" << genOutcome.result().c_str() << std::endl;
    }
    else {
        /* Handle exceptions. */
        std::cout << "GeneratePresignedUrl fail" <<
        ",code:" << genOutcome.error().Code() <<
        ",message:" << genOutcome.error().Message() <<
        ",requestId:" << genOutcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /* Use the signed URL to download the object. */
    auto outcome = client.GetObjectByUrl(genOutcome.result());

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "GetObjectByUrl fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

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

Step 2: Configure hotlink protection

You can configure a Referer whitelist for a bucket to prevent your resources in the bucket from unauthorized access.

For example, you can configure hotlink protection for examplebucket. This way, only requests in which the value of the Referer field is http://www.example.com are allowed. To configure hotlink protection, perform the following steps:

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, click examplebucket.

  3. In the left-side navigation tree, choose Content Security > Hotlink Protection.

  4. On the Hotlink Protection page, turn on Hotlink Protection.

  5. In the Referer Whitelist field, enter http://www.example.com.

  6. Set Allow Empty Referer to No to deny requests in which the Referer field is empty.

  7. Set Truncate QueryString to Yes or No.

    • Yes: Query strings in Referers are removed. For example, if a Referer in hotlink protection configurations is http://www.example.com/?action=nop, the query string is removed and http://www.example.com/ is used to match Referers.

    • No: Query strings in Referers are not removed. For example, if a Referer in hotlink protection configurations is http://www.example.com/?action=nop, http://www.example.com/?action=nop is used to match Referers. For more information about query string parsing, see Query string parsing rules.

  8. Click Save.

For more information about Referers, see Hotlink protection.