Tüm Ürünler
Search
Belge Merkezi

:Python için OSS SDK 1.0 kullanarak erişim kimlik bilgilerini yapılandırma

Son Güncelleme:Oct 01, 2026

Object Storage Service (OSS) SDK for Python kullanarak bir istek başlatmak için kimliğinizi ve erişim izinlerinizi doğrulamak üzere kullanılan erişim kimlik bilgilerini yapılandırmanız gerekir. Kimlik doğrulama ve yetkilendirme gereksinimlerinize bağlı olarak farklı türde erişim kimlik bilgilerini seçebilirsiniz.

Kullanım notları

  • OSS bölgeleri ve uç noktalarının listesi için bkz. Bölgeler ve uç noktalar.

  • Bir RAM kullanıcısı için AccessKey çifti oluşturma hakkında bilgi edinmek için bkz. RAM kullanıcısı için AccessKey çifti oluşturma.

  • Erişim kimlik bilgilerini yapılandırmadan önce Python için OSS SDK'nın en son sürümünün yüklü olduğundan emin olun. Daha fazla bilgi için bkz. Yükleme.

  • alibabacloud-credentials sürümünün 0.3.5 veya daha yenisini kullandığınızdan emin olun. Daha eski bir sürüm hatalara neden olur.

Kimlik bilgisi sağlayıcı başlatma

OSS, bir kimlik bilgisi sağlayıcısını başlatmak için birden çok yöntemi destekler. Gerçek kimlik doğrulama ve yetkilendirme gereksinimlerinize göre uygun bir yöntem seçebilirsiniz.


Başlatma yöntemi


Senaryo


AccessKey çifti veya STS belirteci gerekli mi?


Temel kimlik bilgisi


Kimlik bilgisi geçerlilik süresi


Kimlik bilgisi döndürme veya yenileme yöntemi


RAM kullanıcısının AccessKey çiftini kullanma


Uygulamalar, dış saldırılara karşı savunmasız olmayan güvenli ve kararlı bir ortamda dağıtılır ve çalıştırılır; sık kimlik bilgisi döndürmesi olmadan bulut hizmetlerine uzun süreli erişim gerekir.


Evet


AccessKey çifti


Uzun vadeli


Manuel döndürme


STS tarafından sağlanan geçici erişim kimlik bilgilerini kullanma


Uygulamalar, güvenilir olmayan bir ortamda dağıtılır ve çalıştırılır; bu durumda kimlik bilgilerinin geçerliliğini ve erişilebilecek kaynakları yönetmek istersiniz.


Evet


Security Token Service (STS) belirteci


Geçici


Manuel yenileme


RAM rolünün ARN'sini kullanma


Uygulamalar, hesaplar arası erişim gibi bulut hizmetlerine erişim gerektirir.


Evet


STS belirteci


Geçici


Otomatik yenileme


ECS örneğinin RAM rolünü kullanma


Uygulamalar, Elastic Compute Service (ECS) örneklerinde, Elastic Container Instance üzerinde veya Container Service for Kubernetes (ACK) çalışan düğümlerinde dağıtılır ve çalıştırılır.


Hayır


STS belirteci


Geçici


Otomatik yenileme


OIDC IdP rolünü kullanma


Güvenilmeyen uygulamalar, ACK çalışan düğümlerinde dağıtılır ve çalıştırılır.


Hayır


STS belirteci


Geçici


Otomatik yenileme


Function Compute bağlamındaki Credentials parametresini kullanma


Uygulamalarınızın işlevleri Function Compute içinde dağıtılır ve çalıştırılır.


Hayır


STS belirteci


Geçici


Yenilemeye gerek yok


CredentialsURI kullanma


Uygulamalar, harici sistemlerden erişim kimlik bilgileri gerektirir.


Hayır


STS belirteci


Geçici


Otomatik yenileme


Otomatik olarak dönen AccessKey çifti kullanma


Uygulamalar, AccessKey çiftlerinin sızma riskinin yüksek olduğu bir ortamda dağıtılır ve bulut hizmetlerine uzun vadeli erişim elde etmek için erişim kimlik bilgilerinin sık sık döndürülmesini gerektirir.


Hayır


AccessKey çifti


Uzun vadeli


Otomatik döndürme


Özel erişim kimlik bilgilerini kullanma


Yukarıdaki yöntemlerden hiçbiri gereksinimlerinizi karşılamıyorsa erişim kimlik bilgilerini elde etmek için özel bir yöntem kullanabilirsiniz.


Özel


Özel


Özel


Özel

Yaygın senaryolar için yapılandırma örnekleri

RAM kullanıcısının AccessKey çiftini kullanma

Uygulamanızın sık sık erişim kimlik bilgilerini döndürmeden OSS'ye uzun süreli erişim gerektirdiğini ve dış saldırılara karşı savunmasız olmayan güvenli ve kararlı bir ortamda çalıştığını varsayalım. Bu durumda, Alibaba Cloud hesabınızın veya bir RAM kullanıcısının AccessKey çiftini (bir AccessKey ID ve AccessKey secret) kullanarak bir kimlik bilgisi sağlayıcısını başlatabilirsiniz. Bu yöntemin bir AccessKey çiftini manuel olarak sürdürmenizi gerektirdiğini unutmayın. Bu durum güvenlik riskleri oluşturur ve bakım karmaşıklığını artırır.

Uyarı
  • Bir Alibaba Cloud hesabı kaynakları üzerinde tam izne sahiptir ve AccessKey çiftinin sızması önemli güvenlik riskleri oluşturur. Bu nedenle, bir kimlik bilgisi sağlayıcısını başlatmak için minimum gerekli izinlere sahip bir RAM kullanıcısının AccessKey çiftini kullanmanızı öneririz.

  • Bir RAM kullanıcısı için AccessKey çifti oluşturma hakkında bilgi edinmek için bkz. RAM kullanıcısı için AccessKey çifti oluşturma. Bir RAM kullanıcısının AccessKey çifti yalnızca RAM kullanıcısı oluşturulduğunda görüntülenir. AccessKey çiftini zamanında kaydedin. AccessKey çiftini unutursanız döndürme için yeni bir AccessKey çifti oluşturun.

Ortam değişkenleri

  1. RAM kullanıcısının AccessKey çifti için ortam değişkenlerini yapılandırın.

    Linux

    1. Ortam değişkeni ayarlarını ~/.bashrc dosyasına eklemek için komut satırı arayüzünde aşağıdaki komutları çalıştırın.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın.

        source ~/.bashrc
      2. Ortam değişkenlerinin etkin olup olmadığını kontrol etmek için aşağıdaki komutu çalıştırın.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Varsayılan Shell türünü kontrol etmek için terminalde aşağıdaki komutu çalıştırın.

      echo $SHELL
      1. Varsayılan Shell türüne göre işlemleri gerçekleştirin.

        Zsh

        1. Ortam değişkeni ayarlarını ~/.zshrc dosyasına eklemek için aşağıdaki komutları çalıştırın.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın.

          source ~/.zshrc
        3. Ortam değişkenlerinin etkin olup olmadığını kontrol etmek için aşağıdaki komutu çalıştırın.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Ortam değişkeni ayarlarını ~/.bash_profile dosyasına eklemek için aşağıdaki komutları çalıştırın.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Değişikliklerin etkili olması için aşağıdaki komutu çalıştırın.

          source ~/.bash_profile
        3. Ortam değişkenlerinin etkin olup olmadığını kontrol etmek için aşağıdaki komutu çalıştırın.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. CMD'de aşağıdaki komutları çalıştırın.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Ortam değişkenlerinin etkin olup olmadığını kontrol etmek için aşağıdaki komutu çalıştırın.

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. PowerShell'de aşağıdaki komutları çalıştırın.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Ortam değişkenlerinin etkin olup olmadığını kontrol etmek için aşağıdaki komutu çalıştırın.

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Ayarlarınızın yüklendiğinden emin olmak için IDE, komut satırı aracı, masaüstü uygulamaları ve arka plandaki hizmetler gibi derleme ve çalışma zamanı ortamlarınızı yeniden başlatın veya yenileyin.

  3. Kimlik bilgilerini ortam değişkenlerini kullanarak aktarın.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # 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. 
    region = 'cn-hangzhou'
    
    # Use the AccessKey pair of the RAM user obtained from the environment variables to configure access credentials. Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.

Statik kimlik bilgileri

Aşağıdaki örnek, bir RAM kullanıcısının erişim kimlik bilgilerinin kodda sabit olarak nasıl kodlanacağını gösterir:

Uyarı

Erişim kimlik bilgilerini üretim ortamında dağıtılan uygulama koduna gömmeyin. Bu yöntem yalnızca test amaçlıdır.

# -*- coding: utf-8 -*-
import oss2

# 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 = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the name of the bucket. 
bucket_name = 'yourBucketName'

# 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. 
region = 'cn-hangzhou'

# Enter the AccessKey ID and AccessKey secret of the RAM user.
access_key_id = 'yourAccessKeyID'
access_key_secret = 'yourAccessKeySecret'

# Use the AccessKey pair of the RAM user as access credentials. Note that AuthV4 indicates that the signature algorithm V4 is used. 
auth = oss2.AuthV4(access_key_id, access_key_secret)

# Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.

STS tarafından sağlanan geçici erişim kimlik bilgilerini kullanma

Uygulamanızın OSS'ye geçici olarak erişmesi gerekiyorsa bir AccessKey çifti ve bir STS belirtecinden oluşan STS tarafından sağlanan geçici erişim kimlik bilgilerini kullanabilirsiniz. Bu yöntemin bir STS belirtecini manuel olarak sürdürmenizi gerektirdiğini unutmayın. Bu durum güvenlik riskleri oluşturur ve bakım karmaşıklığını artırır. Mevcut STS belirtecinin süresi dolduktan sonra erişimi uzatmak istiyorsanız STS belirtecini manuel olarak yenilemeniz gerekir.

Önemli
  • AssumeRole API işlemi çağrılarak geçici erişim kimlik bilgileri elde edilebilir. Daha fazla bilgi için bkz. AssumeRole.

  • Geçici erişim kimlik bilgileri SDK kullanılarak da elde edilebilir. Daha fazla bilgi için bkz. STS geçici kimlik bilgilerini kullanarak OSS'ye erişme.

  • Belirteci oluştururken STS belirteci için bir geçerlilik süresi belirtmelisiniz. Süresi dolmuş bir STS belirteci kullanılamaz.

  • STS uç noktalarının listesi için bkz. Uç noktalar.

Ortam değişkenleri

  1. Geçici erişim kimlik bilgileri için ortam değişkenlerini yapılandırın.

    Mac OS X/Linux/Unix

    Uyarı
    • RAM kullanıcısının AccessKey ID'si ve AccessKey secret'ı yerine STS tarafından sağlanan geçici erişim kimlik bilgilerinin (AccessKey ID, AccessKey secret ve STS belirteci) kullanıldığını unutmayın.

    • STS tarafından sağlanan AccessKey ID STS ile başlar. Örnek: STS..

    export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

    Windows

    Uyarı
    • RAM kullanıcısının AccessKey çifti (AccessKey ID ve AccessKey secret) yerine STS tarafından sağlanan geçici erişim kimlik bilgilerinin (AccessKey ID, AccessKey secret ve STS belirteci) kullanıldığını unutmayın.

    • STS tarafından sağlanan AccessKey ID STS ile başlar. Örnek: STS..

    set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
  2. Kimlik bilgisi bilgilerini ortam değişkenlerini kullanarak aktarın.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # 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. 
    region = 'cn-hangzhou'
    
    # Use the AccessKey ID, AccessKey secret, and STS token as access credentials. ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.

Statik kimlik bilgileri

Aşağıdaki örnek, geçici erişim kimlik bilgilerinin kodda nasıl sabit olarak kodlanacağını gösterir:

Uyarı

Erişim kimlik bilgilerini üretim ortamında dağıtılan uygulama koduna gömmeyin. Bu yöntem yalnızca test amaçlıdır.

# -*- coding: utf-8 -*-
import oss2

# Specify the temporary AccessKey ID and AccessKey secret provided by STS, instead of the AccessKey ID and AccessKey secret of an Alibaba Cloud account. 
# Note that an AccessKey ID provided by STS starts with STS. 
sts_access_key_id = 'STS.****************'
sts_access_key_secret = 'yourAccessKeySecret'
# Specify the STS token obtained from STS. 
security_token = 'yourSecurityToken'

# 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 = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the name of the bucket. 
bucket_name = 'yourBucketName'

# 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. 
region = 'cn-hangzhou'

# Initialize the StsAuth instance. Note that auth_version is set to v4, indicating that the signature algorithm V4 is used. 
auth = oss2.StsAuth(sts_access_key_id,
                    sts_access_key_secret,
                    security_token,
                    auth_version="v4")

# Use the StsAuth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.

Diğer senaryolar için yapılandırma örnekleri

RAM rolünün ARN'sini kullanma

Uygulamanıza OSS'ye erişim yetkisi vermeniz gerekiyorsa (örneğin, hesaplar arası erişim senaryosunda) bir kimlik bilgisi sağlayıcısını başlatmak için bir RAM rolünün Alibaba Cloud Resource Name (ARN) değerini kullanabilirsiniz. Bu yöntemin temel mantığı, erişim kimlik bilgilerini yapılandırmak için STS'den alınan bir STS belirtecini kullanmaktır. Credentials aracı, RAM rolünün ARN'sine dayalı olarak bir STS belirteci alır ve oturumun süresi dolmadan önce AssumeRole işlemi çağrılarak STS belirtecini yeniler. RAM rolüne verilen izinleri sınırlamak için bir policy belirtebilirsiniz.

Önemli
  • Bir Alibaba Cloud hesabı kaynakları üzerinde tam izne sahiptir ve AccessKey çiftinin sızması önemli güvenlik riskleri oluşturur. Bu nedenle, bir kimlik bilgisi sağlayıcısını başlatmak için minimum gerekli izinlere sahip bir RAM kullanıcısının AccessKey çiftini kullanmanızı öneririz.

  • Bir RAM kullanıcısı için AccessKey çifti oluşturma hakkında bilgi edinmek için bkz. RAM kullanıcısı için AccessKey çifti oluşturma. Bir RAM kullanıcısının AccessKey çifti yalnızca RAM kullanıcısı oluşturulduğunda görüntülenir. AccessKey çiftini zamanında kaydedin. AccessKey çiftini unutursanız döndürme için yeni bir AccessKey çifti oluşturun.

  • CreateRole işlemi çağrılarak bir RAM rolü oluşturulabilir. RAM rolünün ARN'si yanıtta yer alır. Daha fazla bilgi için bkz. CreateRole.

  1. alibabacloud_credentials bağımlılığını ekleyin.

    pip install alibabacloud_credentials
  2. Erişim kimlik bilgisi olarak AccessKey çiftini ve RAMRoleARN'yi yapılandırın.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    import os
    
    class CredentialProviderWrapper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            credential = self.client.get_credential()
            access_key_id = credential.access_key_id
            access_key_secret = credential.access_key_secret
            security_token = credential.security_token
            return Credentials(access_key_id, access_key_secret, security_token)
    
    config = Config(
        # Obtain the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user from environment variables.
        access_key_id=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        access_key_secret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
        type='ram_role_arn',
        # Specify the ARN of the RAM role that you want your application to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole
        role_arn='<RoleArn>',
        # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        role_session_name='<RoleSessionName>',
        # (Optional) Specify limited permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy='<Policy>',
        # (Optional) Specify the validity period of the role session.
        role_session_expiration=3600
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # 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. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

ECS örneğinin RAM rolünü kullanma

Uygulamanız bir ECS örneğinde, esnek kapsayıcı örneğinde veya bir ACK çalışan düğümünde çalışıyorsa bir kimlik bilgisi sağlayıcısını başlatmak için ECS örneğinin RAM rolünü kullanmanızı öneririz. Bu yöntemin temel mantığı, erişim kimlik bilgilerini yapılandırmak için STS'den alınan bir STS belirtecini kullanmaktır. Örnekteki STS belirtecini otomatik olarak yenilemek için bir ECS örneğine, esnek kapsayıcı örneğine veya bir ACK çalışan düğümüne bir RAM rolü ekleyebilirsiniz. Bu yöntem bir AccessKey çifti veya STS belirteci gerektirmez ve bu kimlik bilgilerini manuel olarak yönetmeyle ilgili riskleri ortadan kaldırır. CreateRole işlemi çağrılarak bir RAM rolü oluşturulabilir. ARN yanıtta yer alır. Daha fazla bilgi için bkz. CreateRole.

  1. alibabacloud_credentials bağımlılığını ekleyin.

    pip install alibabacloud_credentials
  2. Erişim kimlik bilgilerini sağlamak için RAM rolünü kullanın.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    
    class CredentialProviderWrapper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            credential = self.client.get_credential()
            access_key_id = credential.access_key_id
            access_key_secret = credential.access_key_secret
            security_token = credential.security_token
            return Credentials(access_key_id, access_key_secret, security_token)
    
    config = Config(
        type='ecs_ram_role',      # Specify the credential type. Set the value to ecs_ram_role. 
        role_name='<RoleName>'    # Specify the name of the RAM role that is attached to the ECS instance. The RAM role name is optional. If you do not configure this parameter, the system automatically searches for a RAM role. We recommend that you configure this parameter to reduce the number of requests. 
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # 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. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

OIDC IdP rolünü kullanma

ACK çalışan düğümünde RAM rolü yapılandırıldıktan sonra o düğümdeki pod'lar içindeki uygulamalar, bir ECS örneğine dağıtılan bir uygulamaya benzer şekilde, meta veri sunucusunu kullanarak eklenen rol için STS belirtecini alabilir. Ancak, uygulama kodunu size açıklamadan müşteriler tarafından gönderilenler gibi güvenilmeyen uygulamaların, çalışan düğüme eklenen RAM rolünün STS belirtecini almak için meta veri sunucusuna erişmesini istemeyebilirsiniz. Bulut kaynaklarının güvenliğini sağlamak, güvenilmeyen uygulamaların gerekli STS belirtecini güvenli bir şekilde almasına olanak tanımak ve uygulama düzeyindeki izinleri en aza indirmek için Hizmet Hesabı için RAM Rolleri (RRSA) özelliğini kullanabilirsiniz. Bu yöntemin temel mantığı, erişim kimlik bilgilerini yapılandırmak için STS'den alınan bir STS belirtecini kullanmaktır. ACK, farklı uygulama pod'ları için ilgili OpenID Connect (OIDC) belirteci dosyalarını oluşturur ve bunları monte eder ve ilgili yapılandırma bilgilerini ortam değişkenlerine iletir. Credentials aracı, yapılandırma bilgilerini ortam değişkenlerinden alır ve eklenen roller için STS belirtecini almak üzere STS'nin AssumeRoleWithOIDC işlemini çağırır. Bu yöntem bir AccessKey çifti veya STS belirteci gerektirmez ve bu kimlik bilgilerini manuel olarak yönetmeyle ilgili riskleri ortadan kaldırır. Daha fazla bilgi için bkz. Pod düzeyinde erişim kontrolü için RRSA kullanma.

  1. alibabacloud_credentials bağımlılığını ekleyin.

    pip install alibabacloud_credentials
  1. Erişim kimlik bilgisi olarak OIDC IdP'nin rol ARN'sini kullanın.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    import os
    
    class CredentialProviderWrapper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            credential = self.client.get_credential()
            access_key_id = credential.access_key_id
            access_key_secret = credential.access_key_secret
            security_token = credential.security_token
            return Credentials(access_key_id, access_key_secret, security_token)
    
    config = Config(
        # Set the credential type to oidc_role_arn. 
        type='oidc_role_arn',
        # Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
        role_arn=os.environ.get('<RoleArn>'),
        # Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        oidc_provider_arn=os.environ.get('<OidcProviderArn>'),
        # Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        oidc_token_file_path=os.environ.get('<OidcTokenFilePath>'),
        # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        role_session_name='<RoleSessionName>',
        # (Optional) Specify limited permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy='<Policy>',
        # Specify the validity period of the session.
        role_session_expiration=3600
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # 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. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Function Compute bağlamında Credentials kullanma

Uygulamanız için işlev Function Compute içinde dağıtılıp çalıştırılıyorsa Function Compute context bağlamındaki Credentials kullanarak kimlik bilgisi sağlayıcısını başlatabilirsiniz. Bu yöntemin temel mantığı, erişim kimlik bilgilerini yapılandırmak için STS'den alınan bir STS belirtecini kullanmaktır. Function Compute , işlev için yapılandırılan role dayalı olarak bir hizmet rolü üstlenerek bir STS belirteci alır. Ardından, STS belirteci uygulamanıza context bağlamındaki Credentials kullanılarak iletilir. STS belirteci 36 saat boyunca geçerlidir. Geçerlilik süresini değiştiremezsiniz. Bir işlev en fazla 24 saat çalışabilir. İşlev yürütme sırasında STS belirtecini yenilemeniz gerekmez çünkü belirteç işlevin yürütülmesi boyunca geçerli kalır. Bu yöntem bir AccessKey çifti veya STS belirteci gerektirmez ve bu kimlik bilgilerini manuel olarak yönetmeyle ilgili riskleri ortadan kaldırır. Function Compute'a OSS'ye erişim yetkisi verme hakkında daha fazla bilgi için bkz. Diğer bulut hizmetlerine erişmek için işlev rolü kullanma.

  1. Function Compute bağlamındaki Credentials kullanarak kimlik bilgisi sağlayıcısını başlatın.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    
    def handler(event, context):
    
        class CredentialProviderWrapper(CredentialsProvider):
            def get_credentials(self):
                creds = context.credentials
                return Credentials(creds.access_key_id, creds.access_key_secret, creds.security_token)
    
        credentials_provider = CredentialProviderWrapper()
        # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
        auth = oss2.ProviderAuthV4(credentials_provider)
    
        # 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    
        # Specify the name of the bucket. 
        bucket_name = 'yourBucketName'
    
        # 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. 
        region = 'cn-hangzhou'
    
        # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
        bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
        # Use the bucket object for subsequent operations.
    
        return 'success'
    

CredentialsURI kullanma

Uygulamanızın esnek kimlik bilgisi yönetimi ve anahtarsız erişim uygulamak için Alibaba Cloud kimlik bilgilerini harici bir sistemden alması gerekiyorsa bir kimlik bilgisi sağlayıcısını başlatmak için CredentialsURI kullanabilirsiniz. Bu yöntemin temel mantığı, erişim kimlik bilgilerini yapılandırmak için STS'den alınan bir STS belirtecini kullanmaktır. Credentials aracı, istemciyi başlatmak için belirtilen URI'yi kullanarak STS belirtecini alır. Bu yöntem bir AccessKey çifti veya STS belirteci gerektirmez ve bu kimlik bilgilerini manuel olarak yönetmeyle ilgili riskleri ortadan kaldırır.

Önemli
  • CredentialsURI, bir STS belirteci oluşturan sunucunun adresini ifade eder.

  • Kimlik bilgileri URI yanıtını sağlayan arka uç hizmeti, uygulamanızın her zaman geçerli kimlik bilgileri alabilmesini sağlamak için STS belirtecini otomatik olarak yenilemelidir.

  1. Credentials aracının bir STS belirtecini doğru şekilde ayrıştırıp kullanmasına olanak tanımak için URI aşağıdaki gereksinimleri karşılamalıdır:

    • Yanıt durum kodu: 200

    • Yanıt gövdesi yapısı:

      {
          "Code": "Success",
          "AccessKeySecret": "AccessKeySecret",
          "AccessKeyId": "AccessKeyId",
          "Expiration": "2021-09-26T03:46:38Z",
          "SecurityToken": "SecurityToken"
      }
  2. alibabacloud_credentials bağımlılığını ekleyin.

    pip install alibabacloud_credentials
  3. Erişim kimlik bilgisi olarak URI'yi yapılandırın.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    
    class CredentialProviderWrapper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            credential = self.client.get_credential()
            access_key_id = credential.access_key_id
            access_key_secret = credential.access_key_secret
            security_token = credential.security_token
            return Credentials(access_key_id, access_key_secret, security_token)
    
    config = Config(
        type='credentials_uri',
        # Specify the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
        credentials_uri='<CredentialsUri>',
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # 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. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Otomatik olarak dönen AccessKey çifti kullanma

Uygulamanızın OSS'ye uzun vadeli erişime ihtiyacı varsa kimlik bilgisi sızma risklerini azaltmak için AccessKey çiftini manuel olarak döndürmeniz gerekir. Bu durumda, kimlik bilgisi sağlayıcısını başlatmak için bir istemci anahtarı kullanabilirsiniz. Bu yöntemin temel mantığı, OSS kaynaklarına erişmek için bir AccessKey çifti kullanmaktır. Bir istemci anahtarı kullandıktan sonra Key Management Service (KMS), yönetilen bir RAM kullanıcısının AccessKey çiftini otomatik ve düzenli olarak döndürebilir ve RAM kullanıcısının statik AccessKey çiftini dinamik olarak değiştirebilir. Bu durum AccessKey çifti sızma riskini azaltır. KMS ayrıca sızan bir AccessKey çiftini hızla devre dışı bırakmak için anında döndürmeyi destekler. Bu durum, bir AccessKey çiftini manuel olarak sürdürme ihtiyacını ortadan kaldırır ve güvenlik risklerini ve bakım karmaşıklığını azaltır. İstemci anahtarı elde etme hakkında daha fazla bilgi için bkz. Uygulama erişim noktası oluşturma.

  1. Kimlik bilgisi bağımlılıklarını ekleyin.

    pip install aliyun-secret-manager-client
  2. secretsmanager.properties adlı bir yapılandırma dosyası oluşturun.

    # Set the credential type to client_key.
    credentials_type=client_key
    
    # Specify the decryption password of the client key. You can read the decryption password from environment variables or a file.
    client_key_password_from_env_variable=<your client key private key password environment variable name>
    client_key_password_from_file_path=<your client key private key password file path>
    
    # Specify the path of the private key file of the client key.
    client_key_private_key_path=<your client key private key file path>
    
    # Specify the ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"<regionId>"}]
  3. Kimlik bilgilerini yapılandırma dosyasını kullanarak aktarın.

    # -*- coding: utf-8 -*-
    import json
    import oss2
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
    
    class CredentialProviderWrapper(CredentialsProvider):
        def get_credentials(self):
            secret_cache_client = SecretManagerCacheClientBuilder.new_client()
            secret_info = secret_cache_client.get_secret_info("<secretName>")
            secret_value_json = json.loads(secret_info.secret_value)
            return Credentials(secret_value_json["AccessKeyId"], secret_value_json["AccessKeySecret"])
    
    credentials_provider = CredentialProviderWrapper()
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # 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. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Özel erişim kimlik bilgilerini kullanma

Yukarıdaki yöntemlerden hiçbiri gereksinimlerinizi karşılamıyorsa CredentialsProvider işlemini çağırarak erişim kimlik bilgilerini elde etmek için özel bir yöntem belirtebilirsiniz. Temel uygulama bir STS belirtecine dayanıyorsa kimlik bilgisi güncelleme desteği sağlamanız gerektiğini unutmayın.

# -*- coding: utf-8 -*-
import oss2
from oss2 import CredentialsProvider
from oss2.credentials import Credentials

class CredentialProviderWrapper(CredentialsProvider):
    def get_credentials(self):
        # TODO
        # Specify the method used to obtain the custom access credentials.

        # Return long-term access credentials (an AccessKey ID and an AccessKey secret).
        return Credentials('<access_key_id>', '<access_key_secrect>')

        # Return temporary access credentials (an AccessKey ID, an AccessKey secret, and an STS token.
        # Refresh the temporary access credentials based on the validity period. 
        # return Credentials('<access_key_id>', '<access_key_secrect>', '<token>');

credentials_provider = CredentialProviderWrapper()

# Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
auth = oss2.ProviderAuthV4(credentials_provider)

# 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 = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the name of the bucket. 
bucket_name = 'yourBucketName'

# 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. 
region = 'cn-hangzhou'

# Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.