0
# Authentication and Credentials
1
2
Comprehensive authentication system supporting multiple credential types for various deployment scenarios including development environments, production systems, container deployments, and cross-account access patterns.
3
4
## Capabilities
5
6
### Basic API Key Authentication
7
8
Standard authentication using SecretID and SecretKey pairs obtained from Tencent Cloud console.
9
10
```python { .api }
11
class Credential:
12
def __init__(self, secret_id: str, secret_key: str, token: str = None):
13
"""
14
Initialize basic API key credentials.
15
16
Parameters:
17
- secret_id (str): Tencent Cloud Secret ID
18
- secret_key (str): Tencent Cloud Secret Key
19
- token (str, optional): Temporary security token for STS credentials
20
21
Raises:
22
- TencentCloudSDKException: If secret_id or secret_key is None, empty, or contains spaces
23
"""
24
25
def get_credential_info(self):
26
"""
27
Get credential information tuple for API signing.
28
29
Returns:
30
tuple: (secret_id, secret_key, token)
31
"""
32
33
@property
34
def secretId(self) -> str:
35
"""
36
Get secret ID (camelCase accessor for compatibility).
37
38
Returns:
39
str: Secret ID
40
"""
41
42
@property
43
def secretKey(self) -> str:
44
"""
45
Get secret key (camelCase accessor for compatibility).
46
47
Returns:
48
str: Secret key
49
"""
50
```
51
52
**Usage Example:**
53
54
```python
55
from tencentcloud.common import credential
56
57
# Direct credential instantiation (not recommended for production)
58
cred = credential.Credential("your_secret_id", "your_secret_key")
59
60
# With temporary token
61
cred = credential.Credential("secret_id", "secret_key", "temp_token")
62
```
63
64
### Environment Variable Credentials
65
66
Automatically loads credentials from `TENCENTCLOUD_SECRET_ID` and `TENCENTCLOUD_SECRET_KEY` environment variables.
67
68
```python { .api }
69
class EnvironmentVariableCredential:
70
def __init__(self):
71
"""
72
Initialize credential provider that reads from environment variables.
73
Looks for TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY.
74
"""
75
76
def get_credential(self):
77
"""
78
Get credentials from environment variables.
79
80
Returns:
81
Credential: Credential object with values from environment
82
83
Raises:
84
TencentCloudSDKException: If environment variables are not set
85
"""
86
```
87
88
**Usage Example:**
89
90
```python
91
import os
92
from tencentcloud.common import credential
93
94
# Set environment variables
95
os.environ['TENCENTCLOUD_SECRET_ID'] = 'your_secret_id'
96
os.environ['TENCENTCLOUD_SECRET_KEY'] = 'your_secret_key'
97
98
# Use environment credential provider
99
cred = credential.EnvironmentVariableCredential().get_credential()
100
```
101
102
### Configuration File Credentials
103
104
Loads credentials from configuration files located at standard paths with INI format.
105
106
```python { .api }
107
class ProfileCredential:
108
def __init__(self):
109
"""
110
Initialize credential provider that reads from configuration file.
111
112
Reads credentials from fixed standard paths:
113
- Linux: ~/.tencentcloud/credentials or /etc/tencentcloud/credentials
114
- Windows: c:\\Users\\NAME\\.tencentcloud\\credentials
115
116
Only reads from "default" profile section.
117
"""
118
119
def get_credential(self):
120
"""
121
Load credentials from configuration file.
122
123
Returns:
124
Credential: Credential object with values from config file
125
126
Raises:
127
TencentCloudSDKException: If config file not found or invalid format
128
"""
129
```
130
131
**Configuration File Format:**
132
133
```ini
134
[default]
135
secret_id = your_secret_id_here
136
secret_key = your_secret_key_here
137
138
[production]
139
secret_id = prod_secret_id
140
secret_key = prod_secret_key
141
```
142
143
**Usage Example:**
144
145
```python
146
from tencentcloud.common import credential
147
148
# Use default profile
149
cred = credential.ProfileCredential().get_credential()
150
151
# Note: ProfileCredential does not support custom profile names or paths
152
# It only reads from "default" section in standard locations
153
```
154
155
### Instance Role Credentials
156
157
Automatically obtains credentials from CVM instance metadata for applications running on Tencent Cloud instances with assigned roles.
158
159
```python { .api }
160
class CVMRoleCredential:
161
def __init__(self, role_name: str = None):
162
"""
163
Initialize CVM instance role credential provider.
164
165
Parameters:
166
- role_name (str, optional): Specific role name (auto-detected if not provided)
167
"""
168
169
def get_credential_info(self):
170
"""
171
Get credential information tuple from CVM instance metadata.
172
173
Returns:
174
tuple: (secret_id, secret_key, token)
175
176
Raises:
177
TencentCloudSDKException: If not running on CVM or role not assigned
178
"""
179
180
@property
181
def secretId(self) -> str:
182
"""
183
Get secret ID (camelCase accessor for compatibility).
184
185
Returns:
186
str: Secret ID from instance metadata
187
"""
188
189
@property
190
def secretKey(self) -> str:
191
"""
192
Get secret key (camelCase accessor for compatibility).
193
194
Returns:
195
str: Secret key from instance metadata
196
"""
197
198
def update_credential(self):
199
"""
200
Force refresh of credentials from metadata service.
201
"""
202
203
def get_role_name(self) -> str:
204
"""
205
Get the role name associated with this instance.
206
207
Returns:
208
str: Role name
209
"""
210
```
211
212
**Usage Example:**
213
214
```python
215
from tencentcloud.common import credential
216
217
# Automatic role detection
218
cred = credential.CVMRoleCredential().get_credential()
219
220
# Specific role name
221
cred = credential.CVMRoleCredential("MyAppRole").get_credential()
222
```
223
224
### STS Assume Role Credentials
225
226
Cross-account access using Security Token Service (STS) to assume roles in different Tencent Cloud accounts.
227
228
```python { .api }
229
class STSAssumeRoleCredential:
230
def __init__(self, secret_id: str, secret_key: str, role_arn: str, role_session_name: str, duration_seconds: int = 7200, endpoint: str = None):
231
"""
232
Initialize STS assume role credential provider.
233
234
Parameters:
235
- secret_id (str): Base account Secret ID
236
- secret_key (str): Base account Secret Key
237
- role_arn (str): ARN of role to assume (format: qcs::cam::account-id:role/role-name)
238
- role_session_name (str): Session identifier for audit purposes
239
- duration_seconds (int): Session duration in seconds (900-7200, default: 7200)
240
- endpoint (str, optional): Custom STS endpoint
241
"""
242
243
def get_credential_info(self):
244
"""
245
Get credential information tuple with automatic refresh.
246
247
Returns:
248
tuple: (secret_id, secret_key, token)
249
250
Raises:
251
TencentCloudSDKException: If role assumption fails or insufficient permissions
252
"""
253
254
@property
255
def secretId(self) -> str:
256
"""
257
Get secret ID (camelCase accessor for compatibility).
258
259
Returns:
260
str: Secret ID from assumed role
261
"""
262
263
@property
264
def secretKey(self) -> str:
265
"""
266
Get secret key (camelCase accessor for compatibility).
267
268
Returns:
269
str: Secret key from assumed role
270
"""
271
272
def get_sts_tmp_role_arn(self) -> str:
273
"""
274
Get the assumed role ARN.
275
276
Returns:
277
str: Role ARN being assumed
278
"""
279
```
280
281
**Usage Example:**
282
283
```python
284
from tencentcloud.common import credential
285
286
# Cross-account role assumption
287
cred = credential.STSAssumeRoleCredential(
288
secret_id="base_account_secret_id",
289
secret_key="base_account_secret_key",
290
role_arn="qcs::cam::100001234567:role/CrossAccountRole",
291
role_session_name="MyAppSession",
292
duration_seconds=3600
293
).get_credential()
294
```
295
296
### OIDC Credentials
297
298
OpenID Connect (OIDC) authentication for cloud-native applications, particularly useful in Kubernetes environments.
299
300
```python { .api }
301
class OIDCRoleArnCredential:
302
def __init__(self, region: str, provider_id: str, web_identity_token: str, role_arn: str, role_session_name: str, duration_seconds: int = 7200, endpoint: str = None):
303
"""
304
Initialize OIDC role ARN credential provider.
305
306
Parameters:
307
- region (str): Tencent Cloud region
308
- provider_id (str): OIDC provider identifier
309
- web_identity_token (str): OIDC identity token (JWT)
310
- role_arn (str): ARN of role to assume
311
- role_session_name (str): Session identifier
312
- duration_seconds (int): Session duration in seconds (900-7200, default: 7200)
313
- endpoint (str, optional): Custom STS endpoint
314
"""
315
316
def get_credential_info(self):
317
"""
318
Get credential information tuple with automatic refresh.
319
320
Returns:
321
tuple: (secret_id, secret_key, token)
322
323
Raises:
324
TencentCloudSDKException: If OIDC token invalid or role assumption fails
325
"""
326
327
@property
328
def secretId(self) -> str:
329
"""
330
Get secret ID (camelCase accessor for compatibility).
331
332
Returns:
333
str: Secret ID from assumed role
334
"""
335
336
@property
337
def secretKey(self) -> str:
338
"""
339
Get secret key (camelCase accessor for compatibility).
340
341
Returns:
342
str: Secret key from assumed role
343
"""
344
345
def refresh(self):
346
"""
347
Manually refresh credentials using OIDC token.
348
"""
349
350
@property
351
def endpoint(self) -> str:
352
"""
353
Get the STS endpoint.
354
355
Returns:
356
str: STS endpoint URL
357
"""
358
359
@endpoint.setter
360
def endpoint(self, endpoint: str):
361
"""
362
Set custom STS endpoint.
363
364
Parameters:
365
- endpoint (str): Custom STS endpoint URL
366
"""
367
368
def get_credential(self):
369
"""
370
Use OIDC token to assume role and get credentials.
371
372
Returns:
373
Credential: Temporary credentials from OIDC authentication
374
375
Raises:
376
TencentCloudSDKException: If OIDC authentication fails
377
"""
378
379
class DefaultTkeOIDCRoleArnProvider:
380
def __init__(self):
381
"""
382
Initialize TKE (Tencent Kubernetes Engine) OIDC credential provider.
383
Automatically detects TKE environment and uses service account tokens.
384
"""
385
386
def get_credential(self):
387
"""
388
Get credentials using TKE OIDC provider.
389
390
Returns:
391
Credential: Credentials for TKE workload identity
392
393
Raises:
394
TencentCloudSDKException: If not in TKE environment or configuration invalid
395
"""
396
```
397
398
**Usage Example:**
399
400
```python
401
from tencentcloud.common import credential
402
403
# Manual OIDC token
404
cred = credential.OIDCRoleArnCredential(
405
oidc_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...",
406
role_arn="qcs::cam::100001234567:role/TkeRole",
407
role_session_name="TkeWorkload"
408
).get_credential()
409
410
# TKE automatic OIDC
411
cred = credential.DefaultTkeOIDCRoleArnProvider().get_credential()
412
```
413
414
### Default Credential Provider Chain
415
416
Automatic credential resolution using a prioritized chain of credential providers, ideal for applications that need to work across different environments.
417
418
```python { .api }
419
class DefaultCredentialProvider:
420
def __init__(self):
421
"""
422
Initialize default credential provider chain.
423
424
Resolution order:
425
1. Environment variables (TENCENTCLOUD_SECRET_ID, TENCENTCLOUD_SECRET_KEY)
426
2. Configuration file (~/.tencentcloud/credentials)
427
3. CVM instance role
428
4. TKE OIDC provider
429
"""
430
431
def get_credential(self):
432
"""
433
Get credentials using provider chain resolution.
434
435
Returns:
436
Credential: First successfully resolved credential from chain
437
438
Raises:
439
TencentCloudSDKException: If no credential provider succeeds
440
"""
441
```
442
443
**Usage Example:**
444
445
```python
446
from tencentcloud.common import credential
447
448
# Automatic credential resolution
449
cred = credential.DefaultCredentialProvider().get_credential()
450
451
# Use in client initialization
452
from tencentcloud.cvm.v20170312 import cvm_client
453
client = cvm_client.CvmClient(cred, "ap-shanghai")
454
```
455
456
## Common Authentication Patterns
457
458
**Development Environment:**
459
```python
460
# Option 1: Environment variables (recommended)
461
from tencentcloud.common import credential
462
cred = credential.EnvironmentVariableCredential().get_credential()
463
464
# Option 2: Configuration file
465
cred = credential.ProfileCredential().get_credential()
466
```
467
468
**Production Environment:**
469
```python
470
# Option 1: Instance role (recommended for CVM)
471
cred = credential.CVMRoleCredential().get_credential()
472
473
# Option 2: Default provider chain (works everywhere)
474
cred = credential.DefaultCredentialProvider().get_credential()
475
```
476
477
**Container/Kubernetes Environment:**
478
```python
479
# TKE with OIDC
480
cred = credential.DefaultTkeOIDCRoleArnProvider().get_credential()
481
482
# Or use default provider chain
483
cred = credential.DefaultCredentialProvider().get_credential()
484
```
485
486
**Cross-Account Access:**
487
```python
488
# STS assume role
489
cred = credential.STSAssumeRoleCredential(
490
"base_secret_id", "base_secret_key",
491
"qcs::cam::target-account:role/TargetRole",
492
"CrossAccountSession"
493
).get_credential()
494
```