This topic describes how to authorize temporary access to Object Storage Service (OSS) by using Security Token Service (STS) or a signed URL.

Note To generate a signed URL for HTTPS, set the protocol in the endpoint to HTTPS.

Use STS to authorize temporary access

You can use STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for users. You can use STS to grant an access credential that has a custom validity period and custom permissions for a third-party application or a Resource Access Management (RAM) user managed by you. For more information about STS, see What is STS?.

STS has the following benefits:

  • You need only to generate an access token and send the access token to a third-party application, instead of exposing your AccessKey pair to the third-party application. You can customize the access permissions and validity period of this token.
  • The access token automatically expires after the validity period. Therefore, you do not need to manually revoke the permissions of an access token.
Note For more information about how to configure STS, see Use a temporary access credential provided by STS to access OSS in OSS Developer Guide. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain a temporary access credential. The temporary access credential contains a security token and a temporary AccessKey pair that consists of an AccessKey ID and an AccessKey secret. The minimum validity period of a temporary access credential is 900 seconds. The maximum validity period of a temporary access credential is the maximum session duration specified by the current role. For more information, see Specify the maximum session duration for a RAM role.

The following code provides an example on how to generate a signed request by using an STS credential:

// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
String endpoint = "yourEndpoint";
// Specify the temporary AccessKey pair obtained from STS. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS. 
String securityToken = "yourSecurityToken";
// Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
//String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampleobject.txt. The full path of the object cannot contain bucket names. 
//String objectName = "exampleobject.txt";

// You can use the AccessKey pair and security token contained in the temporary access credential obtained from STS to create an OSSClient. 
// Create an OSSClient instance. 
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);

// Perform operations on OSS resources, such as upload or download objects. 
// Upload an object. In this example, a local file is uploaded to OSS as an object. 
// Specify the full path of the local file to upload. If the path of the local file is not specified, the file is uploaded to the path of the project to which the sample program belongs. 
//PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File("D:\\localpath\\examplefile.txt"));
//ossClient.putObject(putObjectRequest);

// Download an object to your local computer. If the specified local file already exists, the file is replaced by the downloaded object. If the specified local file does not exist, the local file is created. 
// If the path for the object is not specified, the downloaded object is saved to the path of the project to which the sample program belongs. 
//ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("D:\\localpath\\examplefile.txt"));

// Shut down the OSSClient instance. 
ossClient.shutdown();

Use a signed URL to authorize temporary access

This section provides examples on how to use a signed URL to authorize temporary access.

Note The validity period must be set for an STS temporary account and a signed URL. When you use an STS temporary account to generate a signed URL that is used to perform operations such as object upload and download, the minimum validity period takes precedence. For example, you can set the validity period of your STS temporary account to 1200 seconds, and that of the signed URL to 3600 seconds. You cannot use the signed URL generated by the STS temporary account to upload objects 1200 seconds after the account is generated.
  • Generate a signed URL

    You can generate a signed URL and provide the URL to a visitor for temporary access. When you generate a signed URL, you can specify the validity period of the URL to limit the period of access from visitors. By default, the validity period of a signed URL is 3,600 seconds. The maximum validity period of a signed URL is 32,400 seconds.

    You can add signature information to a URL and provide the URL for a third-party user for authorized access. For more information, see Add signatures to a URL.

  • Generate a signed URL that allows HTTP GET requests

    You can generate a single signed URL or multiple signed URLs that allow HTTP GET requests at a time based on your requirements.

    • Generate a signed URL that allows HTTP GET requests

      The following code provides an example on how to generate a signed URL that allows HTTP GET requests:

      // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
      String endpoint = "yourEndpoint";
      // Specify the temporary AccessKey pair obtained from STS. 
      String accessKeyId = "yourAccessKeyId";
      String accessKeySecret = "yourAccessKeySecret";
      // Specify the security token obtained from STS. 
      String securityToken = "yourSecurityToken";
      // Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
      String bucketName = "examplebucket";
      // Specify the full path of the object. Example: exampleobject.txt. The full path of the object cannot contain bucket names. 
      String objectName = "exampleobject.txt";
      
      // Create an OSSClient instance. 
      OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
      // Set the validity period of the signed URL to 3,600 seconds (1 hour). 
      Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      // Generate the signed URL that allows HTTP GET requests. Visitors can enter the URL in a browser to access specified OSS resources. 
      URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
      System.out.println(url);
      // Shut down the OSSClient instance. 
      ossClient.shutdown();                    
    • Generate multiple signed URLs that allow HTTP GET requests

      The following code provides an example on how to generate multiple signed URLs that allow HTTP GET requests at a time:

      // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
      String endpoint = "yourEndpoint";
      // Specify the temporary AccessKey pair obtained from STS. 
      String accessKeyId = "yourAccessKeyId";
      String accessKeySecret = "yourAccessKeySecret";
      // Specify the security token obtained from STS. 
      String securityToken = "yourSecurityToken";
      // Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
      String bucketName = "examplebucket";
      // Specify the full paths of the objects. Example: exampleobject.txt. The full paths of the objects cannot contain bucket names. 
      // Specify the full paths of the objects to obtain the signed URLs of these objects at a time. 
      String objectNameList [] = {"exampleobject.txt","exampleimage.jpg"};
      
      // Create an OSSClient instance. 
      OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
      // Set the validity period of the signed URLs to 3,600 seconds (1 hour). 
      Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      
      List<URL> urlList = new ArrayList<URL>();
      for(int i=0; i<objectNameList.length; i++){
          URL url = ossClient.generatePresignedUrl(bucketName, objectNameList[i], expiration);
          urlList.add(url);
      }
      // Display the signed URLs. 
      for(URL url:urlList){
          System.out.println(url);
      }
      // Shut down the OSSClient instance. 
      ossClient.shutdown();
  • Generate a signed URL that allows other HTTP requests

    To authorize other users to temporarily perform operations such as object upload and deletion, you must generate a signed URL that allows corresponding HTTP requests. For example, you can generate a signed URL that allows HTTP PUT requests to authorize users to upload objects. You can generate a single signed URL or multiple signed URLs that allow other HTTP requests at a time based on your requirements.

    • Generate a signed URL that allows other HTTP requests

      The following code provides an example on how to generate a single signed URL that allows other HTTP requests:

      // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
      String endpoint = "yourEndpoint";
      // Specify the temporary AccessKey pair obtained from STS. 
      String accessKeyId = "yourAccessKeyId";
      String accessKeySecret = "yourAccessKeySecret";
      // Specify the security token obtained from STS. 
      String securityToken = "yourSecurityToken";
      // Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
      String bucketName = "examplebucket";
      // Specify the full path of the object. Example: exampleobject.txt. The full path of the object cannot contain bucket names. 
      String objectName = "exampleobject.txt";
      
      // You can use the AccessKey pair and security token contained in the temporary access credential obtained from STS to create an OSSClient. 
      // Create an OSSClient instance. 
      OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
      GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
      // Set the validity period of the signed URL to 3,600 seconds (1 hour). 
      Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      request.setExpiration(expiration);
      // Set ContentType. 
      request.setContentType("text/plain");
      // Set user metadata. 
      request.addUserMetadata("author", "aliy");
      
      // Generate the signed URL. 
      URL signedUrl = ossClient.generatePresignedUrl(request);
      System.out.println(signedUrl);
      
      Map<String, String> requestHeaders = new HashMap<String, String>();
      // Set ContentType. Make sure that the ContentType value must be the same as the content type specified when you generate the signed URL. 
      requestHeaders.put(HttpHeaders.CONTENT_TYPE, "text/plain");
      // Set user metadata. 
      requestHeaders.put(OSS_USER_METADATA_PREFIX + "author", "aliy");
      
      // Use the signed URL to upload an object. 
      ossClient.putObject(signedUrl, new ByteArrayInputStream("Hello OSS".getBytes()), -1, requestHeaders, true);
      
      // Shut down the OSSClient instance. 
      ossClient.shutdown();         
    • Generate multiple signed URLs that allow other HTTP requests

      The following code provides an example on how to generate multiple signed URLs that allow other HTTP requests at a time:

      // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
      String endpoint = "yourEndpoint";
      // Specify the temporary AccessKey pair obtained from STS. 
      String accessKeyId = "yourAccessKeyId";
      String accessKeySecret = "yourAccessKeySecret";
      // Specify the security token obtained from STS. 
      String securityToken = "yourSecurityToken";
      // Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
      String bucketName = "examplebucket";
      // Specify the full paths of the objects. Example: exampleobject.txt. The full paths of the objects cannot contain bucket names. 
      // Specify the full paths of the objects to obtain the signed URLs of these objects at a time. 
      String objectNameList [] = {"exampleobject.txt","exampleimage.jpg"};
      String upLoadNameArray [] = {"D:\\localpath\\examplefile1.txt","D:\\localpath\\examplefile2.jpg"};
      
      
      // You can use the AccessKey pair and security token contained in the temporary access credential obtained from STS to create an OSSClient. 
      // Create an OSSClient instance. 
      OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
      // Set the validity period of the signed URLs to 3,600 seconds (1 hour). 
      Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      for(int i=0; i<objectNameList.length; i++){
          GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectNameList[i], HttpMethod.PUT);
          request.setExpiration(expiration);
          // Set ContentType. 
          request.setContentType(DEFAULT_OBJECT_CONTENT_TYPE);
          // Set user metadata. 
          request.addUserMetadata("author", "aliy");
      
          // Generate the signed URLs. 
          URL signedUrl = ossClient.generatePresignedUrl(request);
          // Display the signed URLs. 
          System.out.println(signedUrl);
      
          Map<String, String> requestHeaders = new HashMap<String, String>();
          requestHeaders.put(HttpHeaders.CONTENT_TYPE, DEFAULT_OBJECT_CONTENT_TYPE);
          requestHeaders.put(OSS_USER_METADATA_PREFIX + "author", "aliy");
      
          // If you want to upload a string, use the following method: 
          //ossClient.putObject(signedUrl, new ByteArrayInputStream("Hello OSS".getBytes()), -1, requestHeaders, true);
         
          // Use the signed URLs to upload an object. 
          try {
            ossClient.putObject(signedUrl, new FileInputStream(new File(upLoadNameArray[i])), -1, requestHeaders, true);
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          }
      }
      
      // Shut down the OSSClient instance. 
      ossClient.shutdown();

    Visitors can specify the HttpMethod.PUT parameter and use the signed URL to upload objects.

  • Generate a signed URL with specified parameters

    You can generate a single signed URL or multiple signed URLs that contain specified parameters at a time based on your requirements.

    • Generate a signed URL that contains specified parameters

      The following code provides an example on how to generate a signed URL that contains specified parameters:

      // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
      String endpoint = "yourEndpoint";
      // Specify the temporary AccessKey pair obtained from STS. 
      String accessKeyId = "yourAccessKeyId";
      String accessKeySecret = "yourAccessKeySecret";
      // Specify the security token obtained from STS. 
      String securityToken = "yourSecurityToken";
      // Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
      String bucketName = "examplebucket";
      // Specify the full path of the object. Example: exampleobject.txt. The full path of the object cannot contain bucket names. 
      String objectName = "exampleobject.txt";
      
      // Create an OSSClient instance. 
      OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
      // Create a request. 
      GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName);
      // Set HttpMethod to PUT. 
      generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
      // Add user metadata. 
      generatePresignedUrlRequest.addUserMetadata("author", "baymax");
      // Set ContentType. 
      generatePresignedUrlRequest.setContentType("application/txt");
      // Set the validity period of the signed URL to 3,600 seconds (1 hour). 
      Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      generatePresignedUrlRequest.setExpiration(expiration);
      // Generate the signed URL. 
      URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
      System.out.println(url);
      // Shut down the OSSClient instance. 
      ossClient.shutdown();                    
    • Generate multiple signed URLs that contain specified parameters

      The following code provides an example on how to generate multiple signed URLs that contain specified parameters:

      // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
      String endpoint = "yourEndpoint";
      // Specify the temporary AccessKey pair obtained from STS. 
      String accessKeyId = "yourAccessKeyId";
      String accessKeySecret = "yourAccessKeySecret";
      // Specify the security token obtained from STS. 
      String securityToken = "yourSecurityToken";
      // Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
      String bucketName = "examplebucket";
      // Specify the full paths of the objects. Example: exampleobject.txt. The full paths of the objects cannot contain bucket names. 
      // Specify the full paths of the objects to obtain the signed URLs of these objects at a time. 
      String objectNameList [] = {"exampleobject.txt","exampleimage.jpg"};
      
      // Create an OSSClient instance. 
      OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      // Set the validity period of the signed URLs to 3,600 seconds (1 hour). 
      Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      for(int i=0; i<objectNameList.length; i++){
          // Create a request. 
          GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectNameList[i]);
          // Set HttpMethod to PUT. 
          generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
          // Add user metadata. 
          generatePresignedUrlRequest.addUserMetadata("author", "baymax");
          // Set ContentType. 
          generatePresignedUrlRequest.setContentType("application/txt");
          generatePresignedUrlRequest.setExpiration(expiration);
          // Generate the signed URLs. 
          URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
          // Display the signed URLs. 
          System.out.println(url);
      }
      // Shut down the OSSClient instance. 
      ossClient.shutdown();
  • Use a signed URL to upload or obtain an object
    • Use a signed URL to upload an object

      The following code provides an example on how to upload an object by using a signed URL:

      // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
      String endpoint = "yourEndpoint";
      // Specify the temporary AccessKey pair obtained from STS. 
      String accessKeyId = "yourAccessKeyId";
      String accessKeySecret = "yourAccessKeySecret";
      // Specify the security token obtained from STS. 
      String securityToken = "yourSecurityToken";
      // Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
      String bucketName = "examplebucket";
      // Specify the full path of the object. Example: exampleobject.txt. The full path of the object cannot contain bucket names. 
      String objectName = "exampleobject.txt";
      
      // Create an OSSClient instance. 
      OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
      // Specify the expiration date of the signed URL. 
      Date expiration = null;
      try {
          expiration = DateUtil.parseRfc822Date("Wed, 18 Mar 2022 14:20:00 GMT");
      } catch (ParseException e) {
          e.printStackTrace();
      }
      // Generate the signed URL. 
      GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
      // Set the validity period of the signed URL. 
      request.setExpiration(expiration);
      // Set ContentType. 
      request.setContentType("application/txt");
      // Add user metadata. 
      request.addUserMetadata("author", "aliy");
      // Generate a signed URL that allows HTTP PUT requests. 
      URL signedUrl = ossClient.generatePresignedUrl(request);
      System.out.println("signed url for putObject: " + signedUrl);
      
      // Use the signed URL to send a request. 
      // Specify the full path of the local file to upload. If the path of the local file is not specified, the file is uploaded to the path of the project to which the sample program belongs. 
      File f = new File("D:\\localpath\\examplefile.txt");
      FileInputStream fin = null;
      try {
          fin = new FileInputStream(f);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }
      // Add headers to the PutObject request. 
      Map<String, String> customHeaders = new HashMap<String, String>();
      customHeaders.put("Content-Type", "application/txt");
      customHeaders.put("x-oss-meta-author", "aliy");
      
      PutObjectResult result = ossClient.putObject(signedUrl, fin, f.length(), customHeaders);
      
      // Shut down the OSSClient instance. 
      ossClient.shutdown();                           
    • Use a signed URL to download an object

      The following code provides an example on how to download a specified object by using a signed URL:

      // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
      String endpoint = "yourEndpoint";
      // Specify the temporary AccessKey pair obtained from STS. 
      String accessKeyId = "yourAccessKeyId";
      String accessKeySecret = "yourAccessKeySecret";
      // Specify the security token obtained from STS. 
      String securityToken = "yourSecurityToken";
      // Specify the name of the bucket in which the object you want to access is stored. Example: examplebucket. 
      String bucketName = "examplebucket";
      // Specify the full path of the object. Example: exampleobject.txt. The full path of the object cannot contain bucket names. 
      String objectName = "exampleobject.txt";
      
      // Create an OSSClient instance. 
      OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
      // Specify the expiration date of the signed URL. 
      Date expiration = null;
      try {
          expiration = DateUtil.parseRfc822Date("Wed, 18 Mar 2022 14:20:00 GMT");
      } catch (ParseException e) {
          e.printStackTrace();
      }
      // Generate the signed URL. 
      GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
      // Set the validity period of the signed URL. 
      request.setExpiration(expiration);
      // Generate a signed URL that allows HTTP GET requests. 
      URL signedUrl = ossClient .generatePresignedUrl(request);
      System.out.println("signed url for getObject: " + signedUrl);
      
      // Use the signed URL to send a request. 
      Map<String, String> customHeaders = new HashMap<String, String>();
      // Add headers to the GetObject request. 
      customHeaders.put("Range", "bytes=100-1000");
      OSSObject object = ossClient.getObject(signedUrl,customHeaders);
      
      // Shut down the OSSClient instance. 
      ossClient.shutdown();