github.com/aliyun/credentials-go@v1.4.7/README.md (about) 1 English | [简体中文](README-CN.md) 2 3 # Alibaba Cloud Credentials for Go 4 5 [](https://badge.fury.io/gh/aliyun%2Fcredentials-go) 6 [](https://github.com/aliyun/credentials-go/actions/workflows/go.yml) 7 [](https://codecov.io/gh/aliyun/credentials-go) 8 [](https://packagist.org/packages/alibabacloud/credentials) 9 [](https://goreportcard.com/report/github.com/aliyun/credentials-go) 10 [](https://scrutinizer-ci.com/g/aliyun/credentials-go/?branch=master) 11 12  13 14 Alibaba Cloud Credentials for Go is a tool for Go developers to manage credentials. 15 16 This document introduces how to obtain and use Alibaba Cloud Credentials for Go. 17 18 ## Requirements 19 20 - It's necessary for you to make sure your system have installed a Go environment which is 1.12.x or newer. 21 22 ## Installation 23 24 Use `go get` to install SDK: 25 26 ```sh 27 go get -u github.com/aliyun/credentials-go 28 ``` 29 30 ## Quick Examples 31 32 Before you begin, you need to sign up for an Alibaba Cloud account and retrieve your [Credentials](https://usercenter.console.aliyun.com/#/manage/ak). 33 34 ### Credential Type 35 36 #### Default credential provider chain 37 38 If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. For more information, see the Default credential provider chain section of this topic. 39 40 ```go 41 import ( 42 "fmt" 43 44 "github.com/aliyun/credentials-go/credentials" 45 ) 46 47 func main(){ 48 provider, err := credentials.NewCredential(nil) 49 if err != nil { 50 return 51 } 52 credential, err := provider.GetCredential() 53 if err != nil { 54 return 55 } 56 accessKeyId := credential.AccessKeyId 57 accessSecret := credential.AccessKeySecret 58 securityToken := credential.SecurityToken 59 credentialType := credential.Type 60 fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) 61 } 62 ``` 63 64 #### AccessKey 65 66 Setup access_key credential through [User Information Management][ak], it have full authority over the account, please keep it safe. Sometimes for security reasons, you cannot hand over a primary account AccessKey with full access to the developer of a project. You may create a sub-account [RAM Sub-account][ram] , grant its [authorization][permissions],and use the AccessKey of RAM Sub-account. 67 68 ```go 69 import ( 70 "fmt" 71 72 "github.com/aliyun/credentials-go/credentials" 73 ) 74 75 func main(){ 76 config := new(credentials.Config). 77 // Which type of credential you want 78 SetType("access_key"). 79 // AccessKeyId of your account 80 SetAccessKeyId("AccessKeyId"). 81 // AccessKeySecret of your account 82 SetAccessKeySecret("AccessKeySecret") 83 84 provider, err := credentials.NewCredential(config) 85 if err != nil { 86 return 87 } 88 89 credential, err := provider.GetCredential() 90 if err != nil { 91 return 92 } 93 94 accessKeyId := credential.AccessKeyId 95 accessKeySecret := credential.AccessKeySecret 96 credentialType := credential.Type 97 fmt.Println(accessKeyId, accessKeySecret, credentialType) 98 } 99 ``` 100 101 #### STS 102 103 Create a temporary security credential by applying Temporary Security Credentials (TSC) through the Security Token Service (STS). 104 105 ```go 106 import ( 107 "fmt" 108 109 "github.com/aliyun/credentials-go/credentials" 110 ) 111 112 func main() { 113 config := new(credentials.Config). 114 // Which type of credential you want 115 SetType("sts"). 116 // AccessKeyId of your account 117 SetAccessKeyId("AccessKeyId"). 118 // AccessKeySecret of your account 119 SetAccessKeySecret("AccessKeySecret"). 120 // Temporary Security Token 121 SetSecurityToken("SecurityToken") 122 123 provider, err := credentials.NewCredential(config) 124 if err != nil { 125 return 126 } 127 128 credential, err := provider.GetCredential() 129 if err != nil { 130 return 131 } 132 133 accessKeyId := credential.AccessKeyId 134 accessKeySecret := credential.AccessKeySecret 135 securityToken := credential.SecurityToken 136 credentialType := credential.Type 137 138 fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) 139 } 140 ``` 141 142 #### AssumeRoleWithOIDC 143 144 After you attach a RAM role to a worker node in an Container Service for Kubernetes, applications in the pods on the worker node can use the metadata server to obtain an STS token the same way in which applications on ECS instances do. However, if an untrusted application is deployed on the worker node, such as an application that is submitted by your customer and whose code is unavailable to you, you may not want the application to use the metadata server to obtain an STS token of the RAM role attached to the worker node. To ensure the security of cloud resources and enable untrusted applications to securely obtain required STS tokens, you can use the RAM Roles for Service Accounts (RRSA) feature to grant minimum necessary permissions to an application. In this case, the ACK cluster creates a service account OpenID Connect (OIDC) token file, associates the token file with a pod, and then injects relevant environment variables into the pod. Then, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS and obtains an STS token of the RAM role. For more information about the RRSA feature, see [Use RRSA to authorize different pods to access different cloud services](https://www.alibabacloud.com/help/en/ack/ack-managed-and-ack-dedicated/user-guide/use-rrsa-to-authorize-pods-to-access-different-cloud-services#task-2142941). 145 146 ``` go 147 package main 148 149 import ( 150 "fmt" 151 "net/http" 152 153 "github.com/aliyun/credentials-go/credentials" 154 ) 155 156 func main() { 157 config := new(credentials.Config). 158 SetType("oidc_role_arn"). 159 // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. 160 SetOIDCProviderArn("OIDCProviderArn"). 161 // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. 162 SetOIDCTokenFilePath("OIDCTokenFilePath"). 163 // Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. 164 SetRoleArn("RoleArn"). 165 // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. 166 SetRoleSessionName("RoleSessionName"). 167 // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}. 168 SetPolicy("Policy"). 169 // Optional. Specify the validity period of the session. 170 SetRoleSessionExpiration(3600). 171 // Optional. The default value is sts.aliyuncs.com. It is recommended to use a regionalized STS domain name. Selecting a region that is geographically closer can ensure network connectivity. For the domain name corresponding to the region, please refer to: https://api.alibabacloud.com/product/Sts 172 SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com") 173 174 provider, err := credentials.NewCredential(config) 175 if err != nil { 176 return 177 } 178 179 credential, err := provider.GetCredential() 180 if err != nil { 181 return 182 } 183 184 accessKeyId := credential.AccessKeyId 185 accessKeySecret := credential.AccessKeySecret 186 securityToken := credential.SecurityToken 187 credentialType := credential.Type 188 189 fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) 190 } 191 ``` 192 193 #### RamRoleArn 194 195 By specifying [RAM Role][RAM Role], the credential will be able to automatically request maintenance of STS Token. If you want to limit the permissions([How to make a policy][policy]) of STS Token, you can assign value for `Policy`. 196 197 ```go 198 import ( 199 "fmt" 200 201 "github.com/aliyun/credentials-go/credentials" 202 ) 203 204 func main(){ 205 config := new(credentials.Config). 206 // Which type of credential you want 207 SetType("ram_role_arn"). 208 // AccessKeyId of your account 209 SetAccessKeyId("AccessKeyId"). 210 // AccessKeySecret of your account 211 SetAccessKeySecret("AccessKeySecret"). 212 // Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole. 213 SetRoleArn("RoleArn"). 214 // Specify the name of the role session. 215 SetRoleSessionName("RoleSessionName"). 216 // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}. 217 SetPolicy("Policy"). 218 // Optional. Specify the expiration of the session 219 SetRoleSessionExpiration(3600). 220 // Optional, role external ID, this parameter is the parameter information provided externally to represent the role, and its main function is to prevent the confused deputy problem. For more information, please refer to: https://www.alibabacloud.com/help/en/ram/use-cases/use-externalid-to-prevent-the-confused-deputy-problem 221 SetExternalId("ExternalId"). 222 // Optional. The default value is sts.aliyuncs.com. It is recommended to use a regionalized STS domain name. Selecting a region that is geographically closer can ensure network connectivity. For the domain name corresponding to the region, please refer to: https://api.alibabacloud.com/product/Sts 223 SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com") 224 225 provider, err := credentials.NewCredential(config) 226 if err != nil { 227 return 228 } 229 credential, err := provider.GetCredential() 230 if err != nil { 231 return 232 } 233 234 accessKeyId := credential.AccessKeyId 235 accessKeySecret := credential.AccessKeySecret 236 securityToken := credential.SecurityToken 237 credentialType := credential.Type 238 239 fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) 240 } 241 ``` 242 243 #### Credentials URI 244 245 By specifying the url, the credential will be able to automatically request maintenance of STS Token. 246 247 ```go 248 import ( 249 "fmt" 250 251 "github.com/aliyun/credentials-go/credentials" 252 ) 253 254 func main(){ 255 config := new(credentials.Config). 256 SetType("credentials_uri"). 257 // Format: http url. `credentialsURI` can be replaced by setting environment variable: ALIBABA_CLOUD_CREDENTIALS_URI 258 SetURL("http://127.0.0.1") 259 provider, err := credentials.NewCredential(config) 260 if err != nil { 261 return 262 } 263 264 credential, err := provider.GetCredential() 265 if err != nil { 266 return 267 } 268 269 accessKeyId := credential.AccessKeyId 270 accessKeySecret := credential.AccessKeySecret 271 securityToken := credential.SecurityToken 272 credentialType := credential.Type 273 274 fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) 275 } 276 ``` 277 278 #### EcsRamRole 279 280 The Credentials tool automatically obtains the RAM role attached to an ECS instance and uses the metadata server of ECS to obtain an STS token. The STS token is then used to initialize a Credentials client. You can also attach a RAM role to an elastic container instance or a worker node in an Alibaba Cloud Container Service for Kubernetes (ACK) cluster. 281 282 ```go 283 import ( 284 "fmt" 285 286 "github.com/aliyun/credentials-go/credentials" 287 ) 288 289 func main(){ 290 config := new(credentials.Config). 291 // Which type of credential you want 292 SetType("ecs_ram_role"). 293 // Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter. 294 SetRoleName("RoleName"). 295 // `DisableIMDSv1` is optional and is recommended to be turned on. It can be replaced by setting environment variable: ALIBABA_CLOUD_IMDSV1_DISABLED 296 SetDisableIMDSv1(true) 297 298 provider, err := credentials.NewCredential(config) 299 if err != nil { 300 return 301 } 302 303 credential, err := provider.GetCredential() 304 if err != nil { 305 return 306 } 307 accessKeyId := credential.AccessKeyId 308 accessKeySecret := credential.AccessKeySecret 309 securityToken := credential.SecurityToken 310 credentialType := credential.Type 311 312 fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) 313 } 314 ``` 315 316 #### Bearer Token 317 318 If credential is required by the Cloud Call Centre (CCC), please apply for Bearer Token maintenance by yourself. 319 320 ```go 321 import ( 322 "fmt" 323 324 "github.com/aliyun/credentials-go/credentials" 325 ) 326 327 func main(){ 328 config := new(credentials.Config). 329 // Which type of credential you want 330 SetType("bearer"). 331 // BearerToken of your account 332 SetBearerToken("BearerToken") 333 334 provider, err := credentials.NewCredential(config) 335 if err != nil { 336 return 337 } 338 339 credential, err := provider.GetCredential() 340 if err != nil { 341 return 342 } 343 344 bearerToken := credential.BearerToken 345 credentialType := credential.Type 346 fmt.Println(bearerToken, credentialType) 347 } 348 ``` 349 350 ### Credential Provider Chain 351 352 If you want to use different types of credentials in the development and production environments of your application, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of the Credentials tool allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you call `NewCredential()` with nil, it will use provider chain to get credential for you. 353 354 ### 1. Environmental certificate 355 356 Look for environment credentials in environment variable. 357 - If the `ALIBABA_CLOUD_ACCESS_KEY_ID` and `ALIBABA_CLOUD_ACCESS_KEY_SECRET` environment variables are defined and are not empty, the program will use them to create default credentials. 358 - If the `ALIBABA_CLOUD_ACCESS_KEY_ID`, `ALIBABA_CLOUD_ACCESS_KEY_SECRET` and `ALIBABA_CLOUD_SECURITY_TOKEN` environment variables are defined and are not empty, the program will use them to create temporary security credentials(STS). Note: This token has an expiration time, it is recommended to use it in a temporary environment. 359 360 ### 2. The RAM role of an OIDC IdP 361 362 If no credentials are found in the previous step, the Credentials tool obtains the values of the following environment variables: 363 364 `ALIBABA_CLOUD_ROLE_ARN`: the ARN of the RAM role. 365 366 `ALIBABA_CLOUD_OIDC_PROVIDER_ARN`: the ARN of the OIDC IdP. 367 368 `ALIBABA_CLOUD_OIDC_TOKEN_FILE`: the path of the OIDC token file. 369 370 If the preceding three environment variables are specified, the Credentials tool uses the environment variables to call the [AssumeRoleWithOIDC](https://www.alibabacloud.com/help/en/ram/developer-reference/api-sts-2015-04-01-assumerolewithoidc) operation of STS to obtain an STS token as the default credential. 371 372 ### 3. Using the config.json Configuration File of Aliyun CLI Tool 373 If there is no higher-priority credential information, the Credentials tool will first check the following locations to see if the config.json file exists: 374 375 Linux system: `~/.aliyun/config.json` 376 Windows system: `C:\Users\USER_NAME\.aliyun\config.json` 377 If the file exists, the program will use the credential information specified by `current` in the configuration file to initialize the credentials client. Of course, you can also use the environment variable `ALIBABA_CLOUD_PROFILE` to specify the credential information, for example by setting the value of `ALIBABA_CLOUD_PROFILE` to `AK`. 378 379 In the config.json configuration file, the value of each module represents different ways to obtain credential information: 380 381 - AK: Use the Access Key of the user as credential information; 382 - RamRoleArn: Use the ARN of the RAM role to obtain credential information; 383 - EcsRamRole: Use the RAM role bound to the ECS to obtain credential information; 384 - OIDC: Obtain credential information through OIDC ARN and OIDC Token; 385 - ChainableRamRoleArn: Use the role chaining method to obtain new credential information by specifying other credentials in the JSON file. 386 387 The configuration example information is as follows: 388 389 ```json 390 { 391 "current": "AK", 392 "profiles": [ 393 { 394 "name": "AK", 395 "mode": "AK", 396 "access_key_id": "access_key_id", 397 "access_key_secret": "access_key_secret" 398 }, 399 { 400 "name": "RamRoleArn", 401 "mode": "RamRoleArn", 402 "access_key_id": "access_key_id", 403 "access_key_secret": "access_key_secret", 404 "ram_role_arn": "ram_role_arn", 405 "ram_session_name": "ram_session_name", 406 "expired_seconds": 3600, 407 "sts_region": "cn-hangzhou" 408 }, 409 { 410 "name": "EcsRamRole", 411 "mode": "EcsRamRole", 412 "ram_role_name": "ram_role_name" 413 }, 414 { 415 "name": "OIDC", 416 "mode": "OIDC", 417 "ram_role_arn": "ram_role_arn", 418 "oidc_token_file": "path/to/oidc/file", 419 "oidc_provider_arn": "oidc_provider_arn", 420 "ram_session_name": "ram_session_name", 421 "expired_seconds": 3600, 422 "sts_region": "cn-hangzhou" 423 }, 424 { 425 "name": "ChainableRamRoleArn", 426 "mode": "ChainableRamRoleArn", 427 "source_profile": "AK", 428 "ram_role_arn": "ram_role_arn", 429 "ram_session_name": "ram_session_name", 430 "expired_seconds": 3600, 431 "sts_region": "cn-hangzhou" 432 } 433 ] 434 } 435 ``` 436 437 ### 4. Configuration file 438 > 439 > If the user's home directory has the default file `~/.alibabacloud/credentials` (Windows is `C:\Users\USER_NAME\.alibabacloud\credentials`), the program will automatically create credentials with the specified type and name. You can also specify the configuration file path by configuring the `ALIBABA_CLOUD_CREDENTIALS_FILE` environment variable. If the configuration file exists, the application initializes a Credentials client by using the credential information that is specified by default in the configuration file. You can also configure the `ALIBABA_CLOUD_PROFILE` environment variable to modify the default credential information that is read. 440 441 Configuration example: 442 ```ini 443 [default] 444 type = access_key # Authentication method is access_key 445 access_key_id = foo # Key 446 access_key_secret = bar # Secret 447 448 [project1] 449 type = ecs_ram_role # Authentication method is ecs_ram_role 450 role_name = EcsRamRoleTest # Role name, optional. It will be retrieved automatically if not set. It is highly recommended to set it up to reduce requests. 451 452 [project2] 453 type = ram_role_arn # Authentication method is ram_role_arn 454 access_key_id = foo 455 access_key_secret = bar 456 role_arn = role_arn 457 role_session_name = session_name 458 459 [project3] 460 type=oidc_role_arn # Authentication method is oidc_role_arn 461 oidc_provider_arn=oidc_provider_arn 462 oidc_token_file_path=oidc_token_file_path 463 role_arn=role_arn 464 role_session_name=session_name 465 ``` 466 467 ### 5. Instance RAM role 468 469 If the environment variable `ALIBABA_CLOUD_ECS_METADATA` is defined and not empty, the program will take the value of the environment variable as the role name and request `http://100.100.100.200/latest/meta-data/ram/security-credentials/` to get the temporary Security credentials are used as default credentials. 470 471 ### 6. Using External Service Credentials URI 472 473 If there are no higher-priority credential information, the Credentials tool will obtain the `ALIBABA_CLOUD_CREDENTIALS_URI` from the environment variables. If it exists, the program will request the URI address to obtain temporary security credentials as the default credential information. 474 475 The external service response structure should be as follows: 476 477 ```json 478 { 479 "Code": "Success", 480 "AccessKeyId": "AccessKeyId", 481 "AccessKeySecret": "AccessKeySecret", 482 "SecurityToken": "SecurityToken", 483 "Expiration": "2024-10-26T03:46:38Z" 484 } 485 ``` 486 487 ## License 488 489 [Apache-2.0](/LICENSE) 490 491 Copyright (c) 2009-present, Alibaba Cloud All rights reserved. 492 493 [ak]: https://usercenter.console.aliyun.com/#/manage/ak 494 [ram]: https://ram.console.aliyun.com/users 495 [policy]: https://www.alibabacloud.com/help/doc-detail/28664.htm?spm=a2c63.p38356.a3.3.27a63b01khWgdh 496 [permissions]: https://ram.console.aliyun.com/permissions 497 [RAM Role]: https://ram.console.aliyun.com/#/role/list