auth.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. package oss
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "fmt"
  8. "hash"
  9. "io"
  10. "net/http"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. )
  15. // headerSorter defines the key-value structure for storing the sorted data in signHeader.
  16. type headerSorter struct {
  17. Keys []string
  18. Vals []string
  19. }
  20. // signHeader signs the header and sets it as the authorization header.
  21. func (conn Conn) signHeader(req *http.Request, canonicalizedResource string) {
  22. akIf := conn.config.GetCredentials()
  23. // Get the final authorization string
  24. authorizationStr := "OSS " + akIf.GetAccessKeyID() + ":" + conn.getSignedStr(req, canonicalizedResource, akIf.GetAccessKeySecret())
  25. // Give the parameter "Authorization" value
  26. req.Header.Set(HTTPHeaderAuthorization, authorizationStr)
  27. }
  28. func (conn Conn) getSignedStr(req *http.Request, canonicalizedResource string, keySecret string) string {
  29. // Find out the "x-oss-"'s address in header of the request
  30. temp := make(map[string]string)
  31. for k, v := range req.Header {
  32. if strings.HasPrefix(strings.ToLower(k), "x-oss-") {
  33. temp[strings.ToLower(k)] = v[0]
  34. }
  35. }
  36. hs := newHeaderSorter(temp)
  37. // Sort the temp by the ascending order
  38. hs.Sort()
  39. // Get the canonicalizedOSSHeaders
  40. canonicalizedOSSHeaders := ""
  41. for i := range hs.Keys {
  42. canonicalizedOSSHeaders += hs.Keys[i] + ":" + hs.Vals[i] + "\n"
  43. }
  44. // Give other parameters values
  45. // when sign URL, date is expires
  46. date := req.Header.Get(HTTPHeaderDate)
  47. contentType := req.Header.Get(HTTPHeaderContentType)
  48. contentMd5 := req.Header.Get(HTTPHeaderContentMD5)
  49. signStr := req.Method + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedOSSHeaders + canonicalizedResource
  50. // convert sign to log for easy to view
  51. if conn.config.LogLevel >= Debug {
  52. var signBuf bytes.Buffer
  53. for i := 0; i < len(signStr); i++ {
  54. if signStr[i] != '\n' {
  55. signBuf.WriteByte(signStr[i])
  56. } else {
  57. signBuf.WriteString("\\n")
  58. }
  59. }
  60. conn.config.WriteLog(Debug, "[Req:%p]signStr:%s\n", req, signBuf.String())
  61. }
  62. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(keySecret))
  63. io.WriteString(h, signStr)
  64. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  65. return signedStr
  66. }
  67. func (conn Conn) getRtmpSignedStr(bucketName, channelName, playlistName string, expiration int64, keySecret string, params map[string]interface{}) string {
  68. if params[HTTPParamAccessKeyID] == nil {
  69. return ""
  70. }
  71. canonResource := fmt.Sprintf("/%s/%s", bucketName, channelName)
  72. canonParamsKeys := []string{}
  73. for key := range params {
  74. if key != HTTPParamAccessKeyID && key != HTTPParamSignature && key != HTTPParamExpires && key != HTTPParamSecurityToken {
  75. canonParamsKeys = append(canonParamsKeys, key)
  76. }
  77. }
  78. sort.Strings(canonParamsKeys)
  79. canonParamsStr := ""
  80. for _, key := range canonParamsKeys {
  81. canonParamsStr = fmt.Sprintf("%s%s:%s\n", canonParamsStr, key, params[key].(string))
  82. }
  83. expireStr := strconv.FormatInt(expiration, 10)
  84. signStr := expireStr + "\n" + canonParamsStr + canonResource
  85. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(keySecret))
  86. io.WriteString(h, signStr)
  87. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  88. return signedStr
  89. }
  90. // newHeaderSorter is an additional function for function SignHeader.
  91. func newHeaderSorter(m map[string]string) *headerSorter {
  92. hs := &headerSorter{
  93. Keys: make([]string, 0, len(m)),
  94. Vals: make([]string, 0, len(m)),
  95. }
  96. for k, v := range m {
  97. hs.Keys = append(hs.Keys, k)
  98. hs.Vals = append(hs.Vals, v)
  99. }
  100. return hs
  101. }
  102. // Sort is an additional function for function SignHeader.
  103. func (hs *headerSorter) Sort() {
  104. sort.Sort(hs)
  105. }
  106. // Len is an additional function for function SignHeader.
  107. func (hs *headerSorter) Len() int {
  108. return len(hs.Vals)
  109. }
  110. // Less is an additional function for function SignHeader.
  111. func (hs *headerSorter) Less(i, j int) bool {
  112. return bytes.Compare([]byte(hs.Keys[i]), []byte(hs.Keys[j])) < 0
  113. }
  114. // Swap is an additional function for function SignHeader.
  115. func (hs *headerSorter) Swap(i, j int) {
  116. hs.Vals[i], hs.Vals[j] = hs.Vals[j], hs.Vals[i]
  117. hs.Keys[i], hs.Keys[j] = hs.Keys[j], hs.Keys[i]
  118. }