获取token代码

This commit is contained in:
tzwang 2023-02-28 10:58:23 +08:00
parent 4b4b190200
commit cc1952f165
2 changed files with 134 additions and 0 deletions

View File

@ -0,0 +1,68 @@
package common
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"time"
)
const (
IAMUser = "pcmmodelarts"
IAMPassword = "!QAZ2wsx3edc4"
IAMDomain = "hw_008618597947378_01"
IAMTokenUrl = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens"
ProjectName = "cn-north-4"
TokenHeader = "X-Subject-Token"
Status_created = 201
)
var (
token, expiredAt = GenerateToken()
)
func GenerateToken() (string, time.Time) {
a := Auth{}
a.Auth.Scope.Project.Name = ProjectName
a.Auth.Identity.Methods = append(a.Auth.Identity.Methods, IAMPassword)
a.Auth.Identity.Password.User.Name = IAMUser
a.Auth.Identity.Password.User.Password = IAMPassword
a.Auth.Identity.Password.User.Domain.Name = IAMDomain
jsonStr, _ := json.Marshal(a)
req_url, err := http.NewRequest("POST", IAMTokenUrl, bytes.NewBuffer(jsonStr))
if err != nil {
log.Fatal(err)
}
defer req_url.Body.Close()
c := http.Client{Timeout: time.Duration(3) * time.Second}
respUrl, err := c.Do(req_url)
if err != nil {
log.Fatal(err)
}
if respUrl.StatusCode != Status_created {
panic("获取token失败")
}
defer respUrl.Body.Close()
var t Token
result, _ := io.ReadAll(respUrl.Body)
json.Unmarshal(result, &t)
return respUrl.Header.Get(TokenHeader), t.Token.ExpiresAt
}
func GetToken() string {
if time.Now().After(expiredAt) {
token, expiredAt = GenerateToken()
}
return token
}

View File

@ -0,0 +1,66 @@
package common
import "time"
type Token struct {
Token struct {
ExpiresAt time.Time `json:"expires_at"`
Methods []string `json:"methods"`
Catalog []struct {
Endpoints []struct {
Id string `json:"id"`
Interface string `json:"interface"`
Region string `json:"region"`
RegionId string `json:"region_id"`
Url string `json:"url"`
} `json:"endpoints"`
Id string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
} `json:"catalog"`
Roles []struct {
Id string `json:"id"`
Name string `json:"name"`
} `json:"roles"`
Project struct {
Domain struct {
Id string `json:"id"`
Name string `json:"name"`
} `json:"domain"`
Id string `json:"id"`
Name string `json:"name"`
} `json:"project"`
IssuedAt time.Time `json:"issued_at"`
User struct {
Domain struct {
Id string `json:"id"`
Name string `json:"name"`
} `json:"domain"`
Id string `json:"id"`
Name string `json:"name"`
PasswordExpiresAt string `json:"password_expires_at"`
} `json:"user"`
} `json:"token"`
}
type Auth struct {
Auth struct {
Identity struct {
Methods []string `json:"methods"`
Password struct {
User struct {
Name string `json:"name"`
Password string `json:"password"`
Domain struct {
Name string `json:"name"`
} `json:"domain"`
} `json:"user"`
} `json:"password"`
} `json:"identity"`
Scope struct {
Project struct {
Name string `json:"name"`
} `json:"project"`
} `json:"scope"`
} `json:"auth"`
}