Para mejorar la seguridad, Object Storage Service (OSS) está retirando Signature V1. Actualice a Signature V4 lo antes posible para que sus aplicaciones sigan funcionando correctamente.
Cómo actualizar de Signature V1 a Signature V4
Siga la guía correspondiente para completar la actualización según su uso actual.
Herramienta | Tipo | Versiones compatibles con V4 | Guía de actualización |
OSS SDK | Java | ||
Python V2 | |||
Python V1 | |||
Go V2 | |||
Go V1 | |||
PHP V2 | |||
PHP V1 | |||
C# V2 | |||
C# V1 | |||
JavaScript | |||
C++ | |||
C | |||
Swift | |||
Objective-C | |||
Android | |||
ossutil | ossutil 2.0 | ||
ossutil 1.0 | |||
ossfs | ossfs 2.0 | ||
ossfs 1.0 | |||
API (construcción manual de firmas) | Para obtener información sobre cómo actualizar un algoritmo de firma V1 construido manualmente a V4, consulte API (manual signature construction). | ||
Consola de OSS | OSS se actualiza automáticamente. Este proceso es transparente para los usuarios. | ||
OSS SDK
Java
Actualice OSS SDK for Java a la versión 3.17.4 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
SignVersion.V4.
Ejemplo de código
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class OSSClientV4 {
public static void main(String[] args) throws Exception {
// Specify the endpoint of the region in which the bucket is located. In this example, the endpoint of the China (Hangzhou) region is used.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the ID of the region of the bucket. In this example, the ID of the China (Hangzhou) region is used: cn-hangzhou.
String region = "cn-hangzhou";
// Obtain credentials from the environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Create an OSSClient instance.
// When you no longer use the OSSClient instance, call the shutdown method to release resources.
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();
// Use the OSSClient instance to initiate requests, such as uploading, downloading, or managing objects.
// When you no longer use the OSSClient instance, call the shutdown method to release resources.
ossClient.shutdown();
}
}
Python
Python V2
Todas las versiones de OSS SDK for Python V2 admiten Signature V4 de forma predeterminada.
-
Cuando inicialice un cliente de OSS con Signature V4, siga este paso:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.
Ejemplo de código
import alibabacloud_oss_v2 as oss
def main():
# Obtain access credentials from environment variables for authentication.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Method 1: Specify only the region.
# 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 cn-hangzhou.
cfg.region = 'cn-hangzhou'
# # Method 2: Specify the endpoint and region.
# # 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 cn-hangzhou.
# cfg.region = 'cn-hangzhou'
# # Specify the public 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.
# # To use the HTTP protocol, set the endpoint to http://oss-cn-hangzhou.aliyuncs.com.
# cfg.endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Use the configuration to create a Client instance.
client = oss.Client(cfg)
# Use the Client instance to perform subsequent operations.
# Call the main function when the script is directly run.
if __name__ == "__main__":
main() # The entry point of the script. When the script is directly run, the main function is called.
Python V1
Actualice OSS SDK for Python V1 a la versión 2.18.4 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
oss2.ProviderAuthV4.
Ejemplo de código
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the environment variables are configured.
auth = oss2.ProviderAuthV4(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.
endpoint = 'yourEndpoint'
# Specify the region of the endpoint. Example: cn-hangzhou.
region = 'cn-hangzhou'
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
Go
Go V2
Todas las versiones de OSS SDK for Go V2 admiten Signature V4 de forma predeterminada.
-
Cuando inicialice un cliente de OSS con Signature V4, siga este paso:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.
Ejemplo de código
package main
import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v/credentials"
)
func main() {
// Method 1: Specify only the region.
// 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 cn-hangzhou.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("cn-hangzhou")
// Method 2: Specify the endpoint and region.
// 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 cn-hangzhou.
// 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. To use the HTTP protocol, set the endpoint to http://oss-cn-hangzhou.aliyuncs.com
// cfg := oss.LoadDefaultConfig().
// WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
// WithRegion("cn-hangzhou").
// WithEndpoint("https://oss-cn-hangzhou.aliyuncs.com")
// Create an OSSClient instance
client := oss.NewClient(cfg)
// Use the OSSClient instance to perform subsequent operations...
}
Go V1
Todas las versiones de OSS SDK for Go V2 admiten Signature V4 de forma predeterminada. Migrate from Go V1 to Go V2.
Actualice OSS SDK for Go V1 a la versión 3.0.2 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
oss.AuthV4.
Ejemplo de código
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// handleError handles unrecoverable errors, logs the error message, and terminates the program.
func handleError(err error) {
log.Fatalf("Error: %v", err)
}
// setupClient sets up and creates an OSS client instance.
// Parameters:
// endpoint - The endpoint of the bucket.
// region - The region that corresponds to the endpoint.
//
// Returns the created OSS client instance.
func setupClient(endpoint, region string) (*oss.Client, error) {
// Obtain access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
return nil, err
}
// Create an OSSClient instance and use a V4 signature.
client, err := oss.New(endpoint, "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region(region))
if err != nil {
return nil, err
}
return client, nil
}
func main() {
// Set yourEndpoint to the endpoint of the bucket. For example, for China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
endpoint := "yourEndpoint"
// Set yourRegion to the region that corresponds to the endpoint, for example, cn-hangzhou.
region := "yourRegion"
// Check if the environment variables are set. Also check for empty strings and placeholder values.
if endpoint == "" || region == "" || endpoint == "yourEndpoint" || region == "yourRegion" {
log.Fatal("Please set yourEndpoint and yourRegion with valid values.")
}
// Set up and create an OSS client instance.
client, err := setupClient(endpoint, region)
if err != nil {
handleError(err)
}
// Print the client information.
log.Printf("Client: %#v\n", client)
}
PHP
PHP V2
Todas las versiones de OSS SDK for PHP V2 admiten Signature V4 de forma predeterminada.
-
Cuando inicialice un cliente de OSS con Signature V4, siga este paso:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
# Load the default configuration of the SDK and specify the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Specify the credential provider.
// Method 1: Specify only the region.
// 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 cn-hangzhou.
$cfg->setRegion(region: "cn-hangzhou");
// // Method 2: Specify the endpoint and region.
// // 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 cn-hangzhou.
// // Specify the public 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.
// // To use the HTTP protocol, set the endpoint to http://oss-cn-hangzhou.aliyuncs.com.
// $cfg->setRegion(region: 'cn-hangzhou')->setEndpoint(endpoint: 'https://oss-cn-hangzhou.aliyuncs.com');
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Use the OSSClient instance to perform subsequent operations.
PHP V1
Actualice OSS SDK for PHP V1 a la versión 2.7.0 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
OSS_SIGNATURE_VERSION_V4.
Ejemplo de código
<?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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
try {
// Obtain access credentials from environment variables and save them to the provider. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the region that corresponds to the endpoint. For example, specify cn-hangzhou.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
C#
C# V2
Todas las versiones de OSS SDK for C# V2 admiten Signature V4 de forma predeterminada.
-
Cuando inicialice un cliente de OSS con Signature V4, siga este paso:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.
using OSS = AlibabaCloud.OSS.V2; // Cree un alias para Alibaba Cloud OSS SDK y así simplificar su uso posterior. var region = "cn-hangzhou"; // Obligatorio. Especifique la región donde se encuentra el bucket. Por ejemplo, si su bucket está en la región China (Hangzhou), establezca la región como cn-hangzhou. var endpoint = null as string; // Opcional. Especifique el endpoint para acceder a OSS. Por ejemplo, si el bucket está en la región China (Hangzhou), establezca el endpoint como https://oss-cn-hangzhou.aliyuncs.com. // Cargue la configuración predeterminada del SDK, que lee automáticamente las credenciales (como el AccessKey) desde las variables de entorno. var cfg = OSS.Configuration.LoadDefault(); // Utilice explícitamente las variables de entorno para obtener las credenciales de autenticación. (Formato: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET) cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider(); // Establezca la región en la configuración. cfg.Region = region; // Si especificó un endpoint, sobrescriba el endpoint predeterminado. if(endpoint != null) { cfg.Endpoint = endpoint; } // Utilice la configuración para crear una instancia de Client. using var client = new OSS.Client(cfg); // Utilice la instancia de Client para ejecutar las operaciones posteriores.
C# V1
Actualice OSS SDK for C# V1 a la versión 2.14.0 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
SignVersion.V4.
Ejemplo de código
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the Endpoint for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the Region ID for the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region ID to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
Node.js
Actualice OSS SDK for Node.js a la versión 6.20.0 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el dedicated OSS region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
oss-cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
authorizationV4.
const OSS = require('ali-oss');
const client = new OSS({
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Set region to the region where the bucket is located. For example, for China (Hangzhou), set region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Use the Signature V4 algorithm.
authorizationV4: true,
// Set bucket to the name of your bucket.
bucket: 'yourBucketName',
// Set endpoint to the public endpoint of the region where the bucket is located. For example, for China (Hangzhou), set endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
});
Browser.js
Actualice OSS SDK for Browser.js a la versión 6.20.0 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el dedicated OSS region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
oss-cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
authorizationV4.
Ejemplo de código
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.20.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
});
</script>
</body>
</html>
C++
Actualice OSS SDK for C++ a la versión 1.10.0 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
SignatureVersionType::V4.
Ejemplo de código
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
C
Actualice OSS SDK for C a la versión 3.11.0 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
signature_version = 4.
Ejemplo de código
#include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize the aos_string_t data type. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME to access OSS. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters. The second parameter in this function specifies the ownership of ctl. By default, the value of the second parameter is 0. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main() {
aos_pool_t *p;
oss_request_options_t *options;
/* Initialize global variables. You need to initialize global variables only once in the program lifecycle. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
return -1;
}
/* Initialize the memory pool and options. */
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_options(options);
/* The logic code. In this example, the logic code is omitted. */
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(p);
/* Release global resources that are allocated. You need to release global resources only once in the program lifecycle. */
aos_http_io_deinitialize();
return 0;
}
Swift
Todas las versiones de OSS SDK for Swift admiten Signature V4 de forma predeterminada.
-
Cuando inicialice un cliente de OSS con Signature V4, siga este paso:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.
import AlibabaCloudOSS
import Foundation
@main
struct Main {
static func main() async {
// Specify the region where the bucket is located. Example: China (Hangzhou) is cn-hangzhou.
let region = "cn-hangzhou"
// Optional. Specify the endpoint to access OSS. For China (Hangzhou), set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
let endpoint: String? = nil
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
let credentialsProvider = EnvironmentCredentialsProvider()
// Configure OSS client parameters.
let config = Configuration.default()
.withRegion(region) // Set the region where the bucket is located.
.withCredentialsProvider(credentialsProvider) // Set the access credentials.
// Set a custom endpoint.
if let endpoint = endpoint {
config.withEndpoint(endpoint)
}
// Create an OSS client instance.
let client = Client(config)
}
}
iOS
Actualice OSS SDK for iOS a la versión 2.11.1 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, siga estos pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
OSSSignVersionV4.
Ejemplo de código
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
NSString *endpoint = @"yourEndpoint";
// The temporary AccessKey pair obtained from STS, which consists of an AccessKey ID and an AccessKey secret.
NSString *accessKeyId = @"yourAccessKeyId";
NSString *accessKeySecret = @"yourAccessKeySecret";
// The security token obtained from STS.
NSString *securityToken = @"yourSecurityToken";
NSString *region = @"yourRegion";
id<OSSCredentialProvider> credentialProvider = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:accessKeySecret securityToken:securityToken];
OSSClientConfiguration *configuration = [OSSClientConfiguration new];
configuration.signVersion = OSSSignVersionV4;
OSSClient *client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credentialProvider clientConfiguration:configuration];
client.region = region;
Android
Actualice OSS SDK for Android a la versión 2.3 o posterior.
-
Cuando inicialice un cliente de OSS con Signature V4, debe completar a continuación los siguientes pasos:
Especifique el region ID del bucket como identificador de la región de la solicitud. Por ejemplo, el ID de región de China (Hangzhou) es
cn-hangzhou.Declare explícitamente el uso del algoritmo de firma V4. Por ejemplo:
SignVersion.V4.
Ejemplo de código
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);
ossutil
ossutil 2.0
Todas las versiones de ossutil 2.0 command line interface admiten Signature V4 de forma predeterminada.
En comparación con Signature V1, cuando utilice Signature V4 debe establecer el parámetro Region en el region ID del bucket al configure ossutil.
Comando de ejemplo
Please enter Region [cn-hangzhou]:cn-hangzhou
ossutil 1.0
Todas las versiones de ossutil 2.0 admiten Signature V4 de forma predeterminada. Migrate from ossutil 1.0 to ossutil 2.0.
La versión 1.7.12 y posteriores de ossutil 1.0 command line interface admiten Signature V4.
En comparación con Signature V1, cuando utilice Signature V4 debe incluir lo siguiente en el comando:
Establezca la opción
--sign-versionenv4.Establezca la opción
--regionen el region ID del bucket.
Comando de ejemplo
./ossutil64 --sign-version v4 --region cn-hangzhou mb oss://examplebucket
ossfs
ossfs 2.0
Todas las versiones de ossfs 2.0 (Preview) admiten Signature V4, pero utilizan Signature V1 de forma predeterminada.
-
Antes de actualizar, ejecute el comando
ossfs --versionpara comprobar la versión actual y complete a continuación los requisitos previos según su versión.ImportanteLa desinstalación interrumpirá sus servicios. Ejecute esta operación fuera del horario de mayor actividad.
Desmonte el sistema de archivos de OSS montado. Reemplace
<mountpoint>por su directorio real.sudo umount <mountpoint>Después de desmontar, siga el comando de ejemplo para actualizar.
En comparación con Signature V1, cuando utilice Signature V4 debe incluir lo siguiente en el comando de montaje:
Establezca la opción
oss_regionen el region ID del bucket.
Comando de ejemplo
ossfs2 mount /tmp/ossfs2-bucket/ -c /etc/ossfs2.conf --oss_region=cn-hongkong
ossfs 1.0
La versión 1.91.4 y posteriores de ossfs 1.0 admiten Signature V4.
-
Antes de actualizar, ejecute el comando
ossfs --versionpara comprobar la versión actual y complete a continuación los requisitos previos según su versión.ImportanteLa desinstalación interrumpirá sus servicios. Ejecute esta operación fuera del horario de mayor actividad.
Actualice a V4 si se cumple el requisito de versión
Desmonte el sistema de archivos de OSS montado. Reemplace
<mountpoint>por su directorio real.sudo umount <mountpoint>Después de desmontar, siga el comando de ejemplo para actualizar.
Actualice a V4 si no se cumple el requisito de versión
-
Desmonte el sistema de archivos de OSS montado. Reemplace
<mountpoint>por su directorio real.sudo umount <mountpoint> -
Desinstale la versión anterior.
Si instaló ossfs mediante un administrador de paquetes, como
aptoyum, ejecute el siguiente comando:sudo apt remove ossfs # For Ubuntu/Debian systems sudo yum remove ossfs # For CentOS/Anolis/Alibaba Cloud Linux systemsSi compiló e instaló ossfs desde el código fuente, vaya al directorio de instalación y ejecute el siguiente comando:
sudo make uninstall
Una vez instalada la nueva versión, siga el comando de ejemplo para actualizar.
-
En comparación con Signature V1, cuando utilice Signature V4 debe incluir lo siguiente en el comando de montaje:
Establezca la opción
sigv4.Establezca la opción
regionen el region ID del bucket.
Comando de ejemplo
ossfs examplebucket -o sigv4 -o region=cn-hangzhou /tmp/ossfs -o url=http://oss-cn-hangzhou.aliyuncs.com
API (construcción manual de la firma)
Utilice un SDK de OSS para enviar solicitudes, ya que el SDK calcula automáticamente la firma. Si no puede usar un SDK de OSS, debe construir manualmente una firma V4 y asegurarse de que la solicitud sea correcta.
|
Método de firma |
Descripción |
Referencias |
|
Incluir la firma en el encabezado |
En OSS, el método más común para verificar la identidad consiste en incluir la firma en el encabezado Authorization de una solicitud HTTP. Todas las operaciones de OSS, excepto las que usan firmas POST o firmas de URL, requieren autenticación mediante el encabezado Authorization. |
|
|
Incluir la firma en la URL |
Puede otorgar acceso de terceros a sus recursos de OSS durante un periodo de validez específico sin revelar sus credenciales de acceso. Para ello, genere una URL firmada que incluya la firma y otra información necesaria de la solicitud. |
|
|
Firma de solicitud POST |
La firma PostObject es un mecanismo que le permite cargar archivos directamente en OSS mediante un formulario HTML. Este mecanismo permite a los usuarios construir un formulario HTML en un cliente, como un navegador web. El formulario incluye campos para el archivo que se va a cargar y otros parámetros necesarios, como la firma, el par de AccessKey, el nombre del bucket y la clave del objeto. Cuando se envía el formulario, esta información se transmite a OSS mediante una solicitud HTTP POST, y OSS verifica la validez de dicha solicitud. |
Cronograma de eliminación de Signature V1 y su impacto
Según el Aviso de suspensión de Signature Version 1 de Alibaba Cloud Object Storage Service, Signature V1 de Alibaba Cloud Object Storage Service se eliminará gradualmente para los nuevos clientes (nuevos UID) a partir del 1 de marzo de 2025. A partir del 1 de septiembre de 2025, Signature V1 dejará de recibir actualizaciones y mantenimiento, y no estará disponible para los nuevos buckets.
Comparación entre Signature V1 y Signature V4
|
Elemento |
||
|
Algoritmo de firma |
HMAC-SHA1 |
HMAC-SHA256 |
|
Periodo de validez de la URL firmada |
La hora de firma puede ser anterior a 7 días. El periodo de validez puede superar los 7 días. |
La hora de firma se limita a los últimos 7 días. El periodo de validez se limita a 7 días. |
|
Construcción de la cadena de firma |
La cadena de firma incluye el método HTTP, Content-MD5, Content-Type, la fecha, los encabezados canónicos y la ruta del recurso. |
La cadena de firma tiene una estructura más compleja, que incluye el método de solicitud, el URI canónico, los parámetros de consulta canónicos, los encabezados canónicos, los encabezados firmados adicionales y el hash de la carga útil. |
|
Encabezados y parámetros de consulta canónicos |
Solo se canonizan los encabezados con el prefijo |
Se canonizan todos los encabezados con el prefijo |
|
Codificación de la ruta del recurso |
La barra diagonal (/) en la ruta del recurso se codifica. |
El carácter |
|
Formato de marca de tiempo y fecha |
Utiliza el formato de fecha HTTP estándar, por ejemplo, Wed, 21 Oct 2015 07:28:00 GMT. |
Utiliza el formato ISO 8601 para la hora UTC, por ejemplo, 20151021T072800Z. |
|
Información de la región |
La firma no incluye información de la región. |
Las reglas de firma introducen el concepto de región. Tanto la cadena de firma como la clave de firma deben incluir el ID de región. |
Preguntas frecuentes
¿Cómo puedo comprobar rápidamente si estoy usando Signature V1 o Signature V4?
Utilice Real-time log query o una herramienta de captura de paquetes, como Wireshark o Fiddler, para consultar el campo Authorization en el encabezado de la solicitud HTTP enviada a OSS.
-
Signature V1: el campo
Authorizationcomienza conOSSy tiene el siguiente formato:Authorization: OSS <AccessKeyId>:<Signature> -
Signature V4: el campo
Authorizationcomienza conOSS4-HMAC-SHA256y tiene el siguiente formato:Authorization: OSS4-HMAC-SHA256 Credential=<AccessKeyId>/<Date>/<Region>/oss/aliyun_v4_request, AdditionalHeaders=<Headers>, Signature=<Signature>
Cómo solucionar un error SignatureDoesNotMatch
Si el cálculo de la firma es incorrecto, el sistema devuelve el código de error SignatureDoesNotMatch. Para localizar rápidamente el problema, compare la información relacionada con la firma generada por el servidor y por el cliente. La respuesta que devuelve el servidor contiene la siguiente información clave:
CanonicalRequest: la cadena de consulta canónica que genera el servidor.StringToSign: la cadena que se firma, generada por el servidor a partir de la solicitud canónica.Signature: el valor final de la firma que calcula el servidor.
Al comparar estos campos con los correspondientes generados por el cliente, puede identificar rápidamente las diferencias y localizar el origen del error. Por ejemplo:
Si
CanonicalRequestno coincide, es posible que el orden de concatenación o el formato de los parámetros de la solicitud sean incorrectos.Si
StringToSignno coincide, es posible que la fecha, la región o la información del producto en la nube estén configuradas de manera incorrecta.Si
Signatureno coincide, podría existir un problema con el cálculo de la clave derivada o con la implementación del algoritmo de firma.