Initialize SDK
Confirm Endpoint
Before configuring the endpoint for SDK usage, please refer to the developer guide section on [IAM Access Domain Name](IAM/API Reference_IAM/Service domain.md) to understand endpoint-related concepts. Baidu AI Cloud currently supports multiple regions. Please refer to Region Selection Guide.
Retrieve access key
To use IAM, users must have valid AK (Access Key ID) and SK (Secret Access Key) credentials for signature authentication. AK/SK are system-assigned strings used to identify users and authenticate signatures for IAM.
Your AK/SK information can be obtained and understood through the following steps:
Register a Baidu AI Cloud account
Create a new IAM client
The regular IAM client acts as the interface for interacting with IAM services, offering developers numerous methods to engage with IAM functionalities.
Create a new IAM client with AK/SK
Users can refer to the following code to create a new IAM Client to access IAM with AK/SK:
1import (
2 "github.com/baidubce/bce-sdk-go/services/iam"
3)
4func main() {
5 // User’s Access Key ID and Secret Access Key
6 ACCESS_KEY_ID, SECRET_ACCESS_KEY := <your-access-key-id>, <your-secret-access-key>
7 // Initialize an IAMClient
8 iamClient, err := iam.NewClient(AK, SK)
9}
In the code above, ACCESS_KEY_ID corresponds to “Access Key ID” in the console. SECRET_ACCESS_KEY corresponds to “Access Key Secret” on the console. Refer to the Guide - How to Retrieve AKSK.
Create an IAM client with STS
Request STS token
IAM facilitates temporary third-party access authorization through the STS mechanism. STS (Security Token Service) is a temporary authorization service provided by Baidu AI Cloud. Using STS, you can generate access credentials with customized permissions and validity periods for third-party users. These users can then use the credentials to directly call Baidu AI Cloud APIs or SDKs, enabling access to designated cloud resources.
To access IAM via STS, users must first request an certification string through the STS client. For instructions on obtaining STS credentials, refer to Baidu AI Cloud STS Usage Guide.
Create an IAM client with STS token
After acquiring the STS token, integrate it into the IAM Client to enable the creation of an IAM client based on STS.
Code example
The GO SDK implements the STS service API. Below is a complete example for requesting an STS Token and creating an IAM Client object:
1import (
2 "fmt"
3 "github.com/baidubce/bce-sdk-go/auth" //Import the authentication module
4 "github.com/baidubce/bce-sdk-go/services/iam" //Import IAM service module
5 "github.com/baidubce/bce-sdk-go/services/sts" //Import the Baige service module
6)
7func main() {
8 //Create a Client object for the STS service, using the default Endpoint
9 AK, SK := <your-access-key-id>, <your-secret-access-key>
10 stsClient, err := sts.NewClient(AK, SK)
11 if err != nil {
12 fmt.Println("create sts client object :", err)
13 return
14 }
15 //Obtain a temporary authentication token with a validity period of 60 seconds and an empty ACL
16 stsObj, err := stsClient.GetSessionToken(60, "")
17 if err != nil {
18 fmt.Println("get session token failed:", err)
19 return
20 }
21 fmt.Println("GetSessionToken result:")
22 fmt.Println(" accessKeyId:", stsObj.AccessKeyId)
23 fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey)
24 fmt.Println(" sessionToken:", stsObj.SessionToken)
25 fmt.Println(" createTime:", stsObj.CreateTime)
26 fmt.Println(" expiration:", stsObj.Expiration)
27 fmt.Println(" userId:", stsObj.UserId)
28 //Create an IAM clientobject using the requested temporary STS, with the default endpoint
29 iamClient, err := iam.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "")
30 if err != nil {
31 fmt.Println("create iam client failed:", err)
32 return
33 }
34 stsCredential, err := auth.NewSessionBceCredentials(
35 stsObj.AccessKeyId,
36 stsObj.SecretAccessKey,
37 stsObj.SessionToken)
38 if err != nil {
39 fmt.Println("create sts credential object failed:", err)
40 return
41 }
42 iamClient.Config.Credentials = stsCredential
43}
Note: Currently, when configuring an IAM client with STS, regardless of where the corresponding IAM service endpoint is located, the STS endpoint must be set to
http://sts.bj.baidubce.com. This default is utilized when creating an STS object in the above code.
Configure HTTPS access to IAM
IAM supports the HTTPS transport protocol. To use HTTPS to access IAM services with the IAM Go SDK, specify HTTPS in the endpoint when creating the IAM client object.
1// import "github.com/baidubce/bce-sdk-go/services/iam"
2 ENDPOINT := "https://iam.bj.baidubce.com" //Specify the use of HTTPS protocol
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4iamClient, _ := iam.NewClientWithEndpoint(AK, SK, ENDPOINT)
Configure the IAM client
If users need to configure specific parameters for the IAM Client, they can customize the configuration using the exported Config field of the IAM Client object after its creation. This allows for configuring parameters such as proxy and maximum number of connections for the client.
Use a proxy
The following code snippet enables the client to access IAM service using a proxy:
1// import "github.com/baidubce/bce-sdk-go/services/iam"
2 // Create an IAM Client object
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4ENDPOINT := "iam.bj.baidubce.com
5client, _ := iam.NewClient(AK, SK, ENDPOINT)
6 // Use the local port 8080 for the proxy
7client.Config.ProxyUrl = "127.0.0.1:8080"
Set network parameters
Users can configure network parameters using the following example code:
1// import "github.com/baidubce/bce-sdk-go/services/iam"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3client, _ := iam.NewClient(AK, SK)
4 // Configure to not retry, default: Back Off retry
5client.Config.Retry = bce.NewNoRetryPolicy()
6 // Configure connection timeout to 30 seconds
7client.Config.ConnectionTimeoutInMillis = 30 * 1000
Configure options for generating signature strings
1// import "github.com/baidubce/bce-sdk-go/services/iam"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3client, _ := iam.NewClient(AK, SK)
4 // Configure the HTTP request header Host for signing
5headersToSign := map[string]struct{}{"Host": struct{}{}}
6client.Config.SignOption.HeadersToSign = HeadersToSign
7 // Configure the validity period of the signature to 30 seconds
8client.Config.SignOption.ExpireSeconds = 30
Parameter description
When using the GO SDK to access IAM, the Config field of the created IAM Client object supports the following parameters, as shown in the table below:
| ConfigMap name | Types | Meaning |
|---|---|---|
| Endpoint | string | Domain name for service requests |
| ProxyUrl | string | The proxy address for client requests |
| Region | string | Region for resource requests |
| UserAgent | string | User name, HTTP request’s User-Agent header |
| Credentials | *auth.BceCredentials | Authentication object for requests, divided into regular AK/SK and STS |
| SignOption | *auth.SignOptions | Options for authentication string signing |
| Retry | RetryPolicy | Retry policy for connections |
| ConnectionTimeoutInMillis | int | Connection timeout, in milliseconds, defaulting to 20 minutes |
Description:
- The
Credentialsis created using theauth.NewBceCredentialsandauth.NewSessionBceCredentialsfunctions. The former is used by default, while the latter is used for STS certification. For details, refer to Create an IAM Client with STS. - The
SignOptionfield represents options when generating a signature string, as detailed in the table below:
| Name | Types | Meaning |
|---|---|---|
| HeadersToSign | map[string]struct{} | HTTP headers used when generating the signature string |
| Timestamp | int64 | Timestamp used in the generated signature string, defaulting to the value at the time of sending request |
| ExpireSeconds | int | Validity period of the signature string |
1 Among configuration options, HeadersToSign defaults to `Host`, `Content-Type`, `Content-Length` and `Content-MD5`; TimeStamp is typically set to zero, indicating that the timestamp at the time of generating the certification string shall be used, and users generally shall not explicitly specify the value for this field; ExpireSeconds defaults to 1,800 seconds or 30 minutes.
- The
Retryfield specifies the retry policy, currently supporting two types:NoRetryPolicyandBackOffRetryPolicy. By default, the latter is used. This retry policy specifies the maximum number of retries, the maximum retry duration, and the retry base. Retries increase exponentially based on the retry base multiplied by 2 until the maximum number of retries or the maximum retry duration is reached.
