token.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. package baiduv2
  2. import (
  3. "context"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "net/http"
  10. "strings"
  11. "time"
  12. "github.com/bytedance/sonic"
  13. "github.com/patrickmn/go-cache"
  14. log "github.com/sirupsen/logrus"
  15. )
  16. var tokenCache = cache.New(time.Hour*23, time.Minute)
  17. func GetBearerToken(ctx context.Context, apiKey string) (string, error) {
  18. parts := strings.Split(apiKey, "|")
  19. if len(parts) != 2 {
  20. return "", errors.New("invalid baidu apikey")
  21. }
  22. if val, ok := tokenCache.Get(apiKey); ok {
  23. token, ok := val.(string)
  24. if !ok {
  25. panic(fmt.Sprintf("invalid cache value type: %T", val))
  26. }
  27. return token, nil
  28. }
  29. tokenResponse, err := getBaiduAccessTokenHelper(ctx, apiKey)
  30. if err != nil {
  31. log.Errorf("get baiduv2 access token failed: %v", err)
  32. return "", errors.New("get baiduv2 access token failed")
  33. }
  34. tokenCache.Set(
  35. apiKey,
  36. tokenResponse.Token,
  37. time.Until(tokenResponse.ExpireTime.Add(-time.Minute*10)),
  38. )
  39. return tokenResponse.Token, nil
  40. }
  41. type TokenResponse struct {
  42. ExpireTime time.Time `json:"expireTime"`
  43. Token string `json:"token"`
  44. }
  45. func getBaiduAccessTokenHelper(ctx context.Context, apiKey string) (*TokenResponse, error) {
  46. ak, sk, err := getAKAndSK(apiKey)
  47. if err != nil {
  48. return nil, err
  49. }
  50. authorization := generateAuthorizationString(ak, sk)
  51. req, err := http.NewRequestWithContext(
  52. ctx,
  53. http.MethodGet,
  54. "https://iam.bj.baidubce.com/v1/BCE-BEARER/token",
  55. nil,
  56. )
  57. if err != nil {
  58. return nil, err
  59. }
  60. query := req.URL.Query()
  61. query.Add("expireInSeconds", "86400")
  62. req.URL.RawQuery = query.Encode()
  63. req.Header.Set("Authorization", authorization)
  64. res, err := http.DefaultClient.Do(req)
  65. if err != nil {
  66. return nil, err
  67. }
  68. defer res.Body.Close()
  69. if res.StatusCode != http.StatusCreated {
  70. return nil, fmt.Errorf("get token failed, status code: %d", res.StatusCode)
  71. }
  72. var tokenResponse TokenResponse
  73. err = sonic.ConfigDefault.NewDecoder(res.Body).Decode(&tokenResponse)
  74. if err != nil {
  75. return nil, err
  76. }
  77. return &tokenResponse, nil
  78. }
  79. func generateAuthorizationString(ak, sk string) string {
  80. httpMethod := http.MethodGet
  81. uri := "/v1/BCE-BEARER/token"
  82. queryString := "expireInSeconds=86400"
  83. hostHeader := "iam.bj.baidubce.com"
  84. canonicalRequest := fmt.Sprintf("%s\n%s\n%s\nhost:%s", httpMethod, uri, queryString, hostHeader)
  85. timestamp := time.Now().UTC().Format("2006-01-02T15:04:05Z")
  86. expirationPeriodInSeconds := 1800
  87. authStringPrefix := fmt.Sprintf(
  88. "bce-auth-v1/%s/%s/%d",
  89. ak,
  90. timestamp,
  91. expirationPeriodInSeconds,
  92. )
  93. signingKey := hmacSHA256(sk, authStringPrefix)
  94. signature := hmacSHA256(signingKey, canonicalRequest)
  95. signedHeaders := "host"
  96. authorization := fmt.Sprintf("%s/%s/%s", authStringPrefix, signedHeaders, signature)
  97. return authorization
  98. }
  99. func hmacSHA256(key, data string) string {
  100. h := hmac.New(sha256.New, []byte(key))
  101. h.Write([]byte(data))
  102. return hex.EncodeToString(h.Sum(nil))
  103. }