12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package oss
- import (
- "context"
- "encoding/json"
- "fmt"
- "go-nc/configs/global"
- "time"
- "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
- "github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
- )
- var ctx = context.Background()
- // 获取临时凭证
- func GetAliyunStsClientCredential() (interface{}, error) {
- // 从 Redis 获取 STS 临时凭证
- info, err := global.App.Redis.Get(ctx, "STSServiceValue").Result()
- if err == nil && info != "" {
- var result interface{}
- err = json.Unmarshal([]byte(info), &result)
- if err != nil {
- return nil, err
- }
- return result, nil
- }
- // 如果 Redis 中没有临时凭证,则获取新的 STS 临时凭证
- accessKeyId := "LTAI5tBqSRASM72SvDex93CF"
- accessKeySecret := "dJJAuwW0TzoHNlHThHPvJboGtrUIXt"
- roleArn := "acs:ram::1781427438729339:role/ramosstest"
- region := "cn-beijing"
- durationSeconds := 3600
- // 创建 STS 客户端
- client, err := sts.NewClientWithAccessKey(region, accessKeyId, accessKeySecret)
- if err != nil {
- return nil, fmt.Errorf("failed to create STS client: %v", err)
- }
- // 创建 AssumeRole 请求
- request := sts.CreateAssumeRoleRequest()
- request.Scheme = "https"
- request.RoleArn = roleArn
- request.RoleSessionName = "external-username"
- request.DurationSeconds = requests.NewInteger(durationSeconds)
- // 获取临时凭证
- response, err := client.AssumeRole(request)
- if err != nil {
- return nil, fmt.Errorf("failed to assume role: %v", err)
- }
- // 将临时凭证存入 Redis
- credentials := response.Credentials
- credJSON, err := json.Marshal(credentials)
- if err != nil {
- return nil, fmt.Errorf("failed to marshal credentials: %v", err)
- }
- // 设置 Redis 键值,设置一个适当的过期时间
- err = global.App.Redis.Set(ctx, "STSServiceValue", credJSON, time.Second*3500).Err()
- if err != nil {
- return nil, fmt.Errorf("failed to set value in Redis: %v", err)
- }
- return credentials, nil
- }
|