0
# Authentication & Credentials
1
2
Multiple authentication methods supporting various credential types for secure access to Alibaba Cloud services. The SDK provides flexible authentication options including access keys, STS tokens, RAM roles, and RSA key pairs.
3
4
## Capabilities
5
6
### Access Key Authentication
7
8
Basic authentication using permanent access key credentials for long-term access to Alibaba Cloud services.
9
10
```python { .api }
11
class AccessKeyCredential:
12
def __init__(self, access_key_id, access_key_secret):
13
"""
14
Initialize access key credential for basic authentication.
15
16
Parameters:
17
- access_key_id (str): Access key ID from Alibaba Cloud console
18
- access_key_secret (str): Access key secret from Alibaba Cloud console
19
"""
20
self.access_key_id = access_key_id
21
self.access_key_secret = access_key_secret
22
```
23
24
### STS Token Authentication
25
26
Temporary authentication using Security Token Service (STS) tokens for short-term, limited-privilege access.
27
28
```python { .api }
29
class StsTokenCredential:
30
def __init__(self, sts_access_key_id, sts_access_key_secret, sts_token):
31
"""
32
Initialize STS token credential for temporary authentication.
33
34
Parameters:
35
- sts_access_key_id (str): Temporary access key ID from STS
36
- sts_access_key_secret (str): Temporary access key secret from STS
37
- sts_token (str): Security token from STS
38
"""
39
self.sts_access_key_id = sts_access_key_id
40
self.sts_access_key_secret = sts_access_key_secret
41
self.sts_token = sts_token
42
```
43
44
### RAM Role ARN Authentication
45
46
Authentication using RAM (Resource Access Management) role assumption for cross-account or delegated access.
47
48
```python { .api }
49
class RamRoleArnCredential:
50
def __init__(self, sts_access_key_id, sts_access_key_secret, role_arn, session_role_name):
51
"""
52
Initialize RAM role ARN credential for role-based authentication.
53
54
Parameters:
55
- sts_access_key_id (str): STS access key ID for role assumption
56
- sts_access_key_secret (str): STS access key secret for role assumption
57
- role_arn (str): ARN of the RAM role to assume
58
- session_role_name (str): Session name for the assumed role
59
"""
60
self.sts_access_key_id = sts_access_key_id
61
self.sts_access_key_secret = sts_access_key_secret
62
self.role_arn = role_arn
63
self.session_role_name = session_role_name
64
```
65
66
### ECS RAM Role Authentication
67
68
Authentication using ECS instance RAM roles for applications running on Alibaba Cloud ECS instances.
69
70
```python { .api }
71
class EcsRamRoleCredential:
72
def __init__(self, role_name):
73
"""
74
Initialize ECS RAM role credential for instance-based authentication.
75
76
Parameters:
77
- role_name (str): Name of the RAM role attached to the ECS instance
78
"""
79
self.role_name = role_name
80
```
81
82
### RSA Key Pair Authentication
83
84
Authentication using RSA key pairs for enhanced security in specific scenarios.
85
86
```python { .api }
87
class RsaKeyPairCredential:
88
def __init__(self, public_key_id, private_key, session_period=3600):
89
"""
90
Initialize RSA key pair credential for public-key authentication.
91
92
Parameters:
93
- public_key_id (str): ID of the uploaded RSA public key
94
- private_key (str): RSA private key content (PEM format)
95
- session_period (int): Session duration in seconds, defaults to 3600
96
"""
97
self.public_key_id = public_key_id
98
self.private_key = private_key
99
self.session_period = session_period
100
```
101
102
### Authentication Signers
103
104
Internal signer classes that handle the cryptographic signing process for different authentication methods.
105
106
```python { .api }
107
class AccessKeySigner:
108
"""Signer for access key authentication."""
109
110
class StsTokenSigner:
111
"""Signer for STS token authentication."""
112
113
class RamRoleArnSigner:
114
"""Signer for RAM role ARN authentication."""
115
116
class EcsRamRoleSigner:
117
"""Signer for ECS RAM role authentication."""
118
119
class RsaKeyPairSigner:
120
"""Signer for RSA key pair authentication."""
121
```
122
123
### Signer Factory
124
125
Factory class for creating appropriate signers based on credential types.
126
127
```python { .api }
128
class SignerFactory:
129
@staticmethod
130
def create_signer(credential, region_id=None):
131
"""
132
Create appropriate signer based on credential type.
133
134
Parameters:
135
- credential: Credential object (AccessKeyCredential, StsTokenCredential, etc.)
136
- region_id (str, optional): Target region ID
137
138
Returns:
139
Signer: Appropriate signer instance for the credential type
140
"""
141
```
142
143
## Usage Examples
144
145
### Basic Access Key Authentication
146
147
```python
148
from aliyunsdkcore.client import AcsClient
149
from aliyunsdkcore.auth.credentials import AccessKeyCredential
150
151
# Create access key credential
152
credential = AccessKeyCredential(
153
access_key_id="LTAI4Gxxxxxxxxxxxxxxxx",
154
access_key_secret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
155
)
156
157
# Initialize client with credential
158
client = AcsClient(credential=credential, region_id="cn-hangzhou")
159
```
160
161
### STS Token Authentication
162
163
```python
164
from aliyunsdkcore.auth.credentials import StsTokenCredential
165
166
# Create STS token credential (typically obtained from STS service)
167
credential = StsTokenCredential(
168
sts_access_key_id="STS.Nxxxxxxxxxxxxxxxx",
169
sts_access_key_secret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
170
sts_token="CAIS8wF1q6Ft5B2yfSjIr5D2K..." # Long STS token
171
)
172
173
client = AcsClient(credential=credential, region_id="cn-beijing")
174
```
175
176
### RAM Role ARN Authentication
177
178
```python
179
from aliyunsdkcore.auth.credentials import RamRoleArnCredential
180
181
# Create RAM role ARN credential
182
credential = RamRoleArnCredential(
183
sts_access_key_id="LTAI4Gxxxxxxxxxxxxxxxx",
184
sts_access_key_secret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
185
role_arn="acs:ram::123456789012****:role/MyRole",
186
session_role_name="MySessionName"
187
)
188
189
client = AcsClient(credential=credential, region_id="cn-shanghai")
190
```
191
192
### ECS RAM Role Authentication
193
194
```python
195
from aliyunsdkcore.auth.credentials import EcsRamRoleCredential
196
197
# Create ECS RAM role credential (for use on ECS instances)
198
credential = EcsRamRoleCredential(role_name="MyEcsRole")
199
200
client = AcsClient(credential=credential, region_id="cn-shenzhen")
201
```
202
203
### RSA Key Pair Authentication
204
205
```python
206
from aliyunsdkcore.auth.credentials import RsaKeyPairCredential
207
208
# Load private key from file
209
with open("private_key.pem", "r") as f:
210
private_key = f.read()
211
212
# Create RSA key pair credential
213
credential = RsaKeyPairCredential(
214
public_key_id="your-public-key-id",
215
private_key=private_key,
216
session_period=7200 # 2 hours
217
)
218
219
client = AcsClient(credential=credential, region_id="cn-qingdao")
220
```
221
222
### Legacy Authentication (Direct Parameters)
223
224
```python
225
# Direct access key parameters (legacy approach)
226
client = AcsClient(
227
ak="LTAI4Gxxxxxxxxxxxxxxxx",
228
secret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
229
region_id="cn-hangzhou"
230
)
231
232
# RSA key pair parameters (legacy approach)
233
client = AcsClient(
234
public_key_id="your-public-key-id",
235
private_key=private_key_content,
236
session_period=3600,
237
region_id="cn-hangzhou"
238
)
239
```
240
241
### Credential Validation
242
243
```python
244
from aliyunsdkcore.acs_exception.exceptions import ClientException
245
246
try:
247
# Create client with credentials
248
client = AcsClient(credential=credential, region_id="cn-hangzhou")
249
250
# Test authentication with a simple request
251
from aliyunsdkcore.request import CommonRequest
252
request = CommonRequest()
253
request.set_domain("ecs.cn-hangzhou.aliyuncs.com")
254
request.set_version("2014-05-26")
255
request.set_action_name("DescribeRegions")
256
request.set_method("POST")
257
258
response = client.do_action_with_exception(request)
259
print("Authentication successful")
260
261
except ClientException as e:
262
if "InvalidAccessKeyId" in e.get_error_code():
263
print("Invalid access key ID")
264
elif "SignatureDoesNotMatch" in e.get_error_code():
265
print("Invalid access key secret or signature error")
266
else:
267
print(f"Authentication error: {e.get_error_msg()}")
268
```
269
270
### Environment-based Authentication
271
272
```python
273
import os
274
from aliyunsdkcore.auth.credentials import AccessKeyCredential
275
276
# Load credentials from environment variables
277
ak = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID")
278
secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
279
280
if ak and secret:
281
credential = AccessKeyCredential(ak, secret)
282
client = AcsClient(credential=credential, region_id="cn-hangzhou")
283
else:
284
raise ValueError("Missing required environment variables")
285
```