Para aumentar a segurança, o Object Storage Service (OSS) está descontinuando a Assinatura V1. Atualize para a Assinatura V4 o mais breve possível para garantir que suas aplicações continuem funcionando corretamente.
Como atualizar da Assinatura V1 para a Assinatura V4
Siga o guia correspondente ao seu uso atual para concluir a atualização.
|
Ferramenta |
Tipo |
Versões com suporte a V4 |
Guia de atualização |
|
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 (construção manual de assinatura) |
Para obter informações sobre como atualizar um algoritmo de assinatura V1 construído manualmente para V4, consulte API (construção manual de assinatura). |
||
|
Console do OSS |
O OSS atualiza automaticamente. O processo é transparente para os usuários. |
||
OSS SDK
Java
Atualize o OSS SDK for Java para a versão 3.17.4 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
SignVersion.V4.
Exemplo 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 as versões do OSS SDK for Python V2 oferecem suporte à Assinatura V4 por padrão.
-
Ao inicializar um OSS Client com a Assinatura V4, execute a etapa a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.
Exemplo de código
Python V1
Atualize o OSS SDK for Python V1 para a versão 2.18.4 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
oss2.ProviderAuthV4.
Exemplo 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 as versões do OSS SDK for Go V2 oferecem suporte à Assinatura V4 por padrão.
-
Ao inicializar um OSS Client com a Assinatura V4, execute a etapa a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.
Exemplo 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 as versões do OSS SDK for Go V2 oferecem suporte à Assinatura V4 por padrão. Migrar do Go V1 para o Go V2.
Atualize o OSS SDK for Go V1 para a versão 3.0.2 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
oss.AuthV4.
Exemplo 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 as versões do OSS SDK for PHP V2 oferecem suporte à Assinatura V4 por padrão.
-
Ao inicializar um OSS Client com a Assinatura V4, execute a etapa a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
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
Atualize o OSS SDK for PHP V1 para a versão 2.7.0 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
OSS_SIGNATURE_VERSION_V4.
Exemplo 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 as versões do OSS SDK for C# V2 oferecem suporte à Assinatura V4 por padrão.
-
Ao inicializar um OSS Client com a Assinatura V4, execute a etapa a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.
C# V1
Atualize o OSS SDK for C# V1 para a versão 2.14.0 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
SignVersion.V4.
Exemplo 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
Atualize o OSS SDK for Node.js para a versão 6.20.0 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região dedicada do OSS do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
oss-cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
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
Atualize o OSS SDK for Browser.js para a versão 6.20.0 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região dedicada do OSS do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
oss-cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
authorizationV4.
Exemplo 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++
Atualize o OSS SDK for C++ para a versão 1.10.0 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
SignatureVersionType::V4.
Exemplo 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
Atualize o OSS SDK for C para a versão 3.11.0 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
signature_version = 4.
Exemplo 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 as versões do OSS SDK for Swift oferecem suporte à Assinatura V4 por padrão.
-
Ao inicializar um OSS Client com a Assinatura V4, execute a etapa a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
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
Atualize o OSS SDK for iOS para a versão 2.11.1 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
OSSSignVersionV4.
Exemplo 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
Atualize o OSS SDK for Android para a versão 2,3 ou posterior.
-
Ao inicializar um OSS Client com a Assinatura V4, execute as etapas a seguir:
Especifique o ID da região do bucket como identificador da região da solicitação. Por exemplo, o ID da região da China (Hangzhou) é
cn-hangzhou.Declare explicitamente o uso do algoritmo de assinatura V4. Exemplo:
SignVersion.V4.
Exemplo 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 as versões da interface de linha de comando ossutil 2,0 oferecem suporte à Assinatura V4 por padrão.
Em comparação com a Assinatura V1, ao usar a Assinatura V4, defina o parâmetro Region como o ID da região do bucket quando configure o ossutil.
Exemplo de comando
Please enter Region [cn-hangzhou]:cn-hangzhou
ossutil 1,0
Todas as versões do ossutil 2,0 oferecem suporte à Assinatura V4 por padrão. Migrar do ossutil 1,0 para o ossutil 2,0.
A versão 1.7.12 e posteriores da interface de linha de comando ossutil 1,0 oferecem suporte à Assinatura V4.
Em comparação com a Assinatura V1, ao usar a Assinatura V4, execute as ações a seguir no comando:
Defina a opção
--sign-versioncomov4.Defina a opção
--regioncomo o ID da região do bucket.
Exemplo de comando
./ossutil64 --sign-version v4 --region cn-hangzhou mb oss://examplebucket
ossfs
ossfs 2,0
Todas as versões do ossfs 2,0 (Visualização) oferecem suporte à Assinatura V4, mas usam a Assinatura V1 por padrão.
-
Antes de atualizar, execute o comando
ossfs --versionpara verificar a versão atual e conclua os pré-requisitos a seguir com base na sua versão.ImportanteA desinstalação interromperá seus serviços. Execute esta operação fora dos horários de pico.
Desmonte o sistema de arquivos do OSS montado. Substitua
<mountpoint>pelo seu diretório real.sudo umount <mountpoint>Após desmontar, siga o exemplo de comando para atualizar.
Em comparação com a Assinatura V1, ao usar a Assinatura V4, execute as ações a seguir no comando de montagem:
Defina a opção
oss_regioncomo o ID da região do bucket.
Exemplo de comando
ossfs2 mount /tmp/ossfs2-bucket/ -c /etc/ossfs2.conf --oss_region=cn-hongkong
ossfs 1,0
A versão 1.91.4 e posteriores do ossfs 1,0 oferecem suporte à Assinatura V4.
-
Antes de atualizar, execute o comando
ossfs --versionpara verificar a versão atual e conclua os pré-requisitos a seguir com base na sua versão.ImportanteA desinstalação interromperá seus serviços. Execute esta operação fora dos horários de pico.
Atualizar para V4 se o requisito de versão for atendido
Desmonte o sistema de arquivos do OSS montado. Substitua
<mountpoint>pelo seu diretório real.sudo umount <mountpoint>Após desmontar, siga o Exemplo de comando para atualizar.
Atualizar para V4 se o requisito de versão não for atendido
-
Desmonte o sistema de arquivos do OSS montado. Substitua
<mountpoint>pelo seu diretório real.sudo umount <mountpoint> -
Desinstale a versão antiga.
Se você instalou o ossfs usando um gerenciador de pacotes, como
aptouyum, execute o seguinte comando:sudo apt remove ossfs # For Ubuntu/Debian systems sudo yum remove ossfs # For CentOS/Anolis/Alibaba Cloud Linux systemsSe você compilou e instalou o ossfs a partir do código-fonte, vá para o diretório de instalação e execute o seguinte comando:
sudo make uninstall
Após instalar a nova versão, siga o Exemplo de comando para atualizar.
-
Em comparação com a Assinatura V1, ao usar a Assinatura V4, execute as ações a seguir no comando de montagem:
Defina a opção
sigv4.Defina a opção
regioncomo o ID da região do bucket.
Exemplo de comando
ossfs examplebucket -o sigv4 -o region=cn-hangzhou /tmp/ossfs -o url=http://oss-cn-hangzhou.aliyuncs.com
API (construção manual de assinatura)
Use um OSS SDK para enviar solicitações, pois o SDK calcula a assinatura automaticamente. Se não for possível usar um OSS SDK, construa manualmente uma assinatura V4 e garanta que a solicitação esteja correta.
|
Método de assinatura |
Descrição |
Referências |
|
Incluir a assinatura no cabeçalho |
No OSS, o método mais comum para verificação de identidade é incluir a assinatura no cabeçalho Authorization de uma solicitação HTTP. Todas as operações do OSS, exceto aquelas que usam assinaturas POST ou assinaturas de URL, exigem autenticação por meio do cabeçalho Authorization. |
|
|
Incluir a assinatura na URL |
Conceda acesso de terceiros aos seus recursos do OSS por um período de validade específico sem revelar suas credenciais de acesso, gerando uma URL assinada que inclui a assinatura e outras informações necessárias da solicitação. |
|
|
Assinatura de solicitação POST |
A assinatura PostObject é um mecanismo que permite carregar arquivos diretamente no OSS por meio de um formulário HTML. Esse mecanismo permite que os usuários construam um formulário HTML em um cliente, como um navegador web. O formulário inclui campos para o arquivo a ser carregado e outros parâmetros necessários, como a assinatura, o par de AccessKey, o nome do bucket e a chave do objeto. Quando o formulário é enviado, essas informações são enviadas ao OSS por meio de uma solicitação HTTP POST, e o OSS verifica a validade da solicitação POST. |
Cronograma de descontinuação da Assinatura V1 e impacto
De acordo com o Aviso de Descontinuação da Versão 1 da Assinatura do Alibaba Cloud Object Storage Service, a Assinatura V1 para o Alibaba Cloud Object Storage Service será gradualmente descontinuada para novos clientes (novos UIDs) a partir de 1º de março de 2025. A partir de 1º de setembro de 2025, a Assinatura V1 não receberá mais atualizações ou manutenção e não estará disponível para novos buckets.
Comparação entre Assinatura V1 e Assinatura V4
|
Item |
||
|
Algoritmo de assinatura |
HMAC-SHA1 |
HMAC-SHA256 |
|
Período de validade da URL assinada |
O momento da assinatura pode ser superior a 7 dias no passado. O período de validade pode exceder 7 dias. |
O momento da assinatura limita-se aos últimos 7 dias. O período de validade limita-se a 7 dias. |
|
Construção da string de assinatura |
A string de assinatura inclui o método HTTP, Content-MD5, Content-Type, data, cabeçalhos canonizados e caminho do recurso. |
A string de assinatura possui uma estrutura mais complexa, que inclui o método de solicitação, URI canonizado, parâmetros de consulta canonizados, cabeçalhos canonizados, cabeçalhos assinados adicionais e hash do payload. |
|
Cabeçalhos e parâmetros de consulta canonizados |
Apenas cabeçalhos com o prefixo |
Todos os cabeçalhos com o prefixo |
|
Codificação do caminho do recurso |
A barra (/) no caminho do recurso é codificada. |
O |
|
Formato de timestamp e data |
Usa o formato de data HTTP padrão, por exemplo, Wed, 21 Oct 2015 07:28:00 GMT. |
Usa o formato ISO 8601 para hora UTC, por exemplo, 20151021T072800Z. |
|
Informações da região |
A assinatura não inclui informações da região. |
As regras de assinatura introduzem o conceito de região. Tanto a string de assinatura quanto a chave de assinatura devem incluir o ID da região. |
Perguntas frequentes
Como verificar rapidamente se estou usando a Assinatura V1 ou a Assinatura V4?
Use a Consulta de log em tempo real ou uma ferramenta de captura de pacotes, como Wireshark ou Fiddler, para visualizar o campo Authorization no cabeçalho da solicitação HTTP enviada ao OSS.
-
Assinatura V1: O campo
Authorizationcomeça comOSSe tem o seguinte formato:Authorization: OSS <AccessKeyId>:<Signature> -
Assinatura V4: O campo
Authorizationcomeça comOSS4-HMAC-SHA256e tem o seguinte formato:Authorization: OSS4-HMAC-SHA256 Credential=<AccessKeyId>/<Date>/<Region>/oss/aliyun_v4_request, AdditionalHeaders=<Headers>, Signature=<Signature>
Como solucionar um erro SignatureDoesNotMatch
Se o cálculo da assinatura estiver incorreto, o sistema retornará o código de erro SignatureDoesNotMatch. Para localizar rapidamente o problema, compare as informações relacionadas à assinatura geradas pelo servidor e pelo cliente. A resposta retornada pelo servidor contém as seguintes informações principais:
CanonicalRequest: A string de consulta canonizada gerada pelo servidor.StringToSign: A string a ser assinada gerada pelo servidor com base na solicitação canonizada.Signature: O valor final da assinatura calculado pelo servidor.
Ao comparar esses campos com os campos correspondentes gerados pelo cliente, identifique rapidamente as diferenças e localize a origem do erro. Por exemplo:
Se
CanonicalRequestfor inconsistente, a ordem de concatenação ou o formato dos parâmetros da solicitação podem estar incorretos.Se
StringToSignfor inconsistente, a data, a região ou as informações do produto de nuvem podem estar definidas incorretamente.Se
Signaturefor inconsistente, pode haver um problema com o cálculo da chave derivada ou com a implementação do algoritmo de assinatura.