This repository has been archived by the owner on May 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathauth.go
executable file
·73 lines (63 loc) · 1.63 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package auth
import (
"crypto/hmac"
"crypto/sha256"
"fmt"
"net/http"
hws_cloud "github.com/huaweicse/auth/third_party/forked/datastream/aws"
)
// Headers for ak/sk auth
const (
HeaderServiceAk = "X-Service-AK"
HeaderServiceShaAKSK = "X-Service-ShaAKSK"
HeaderServiceProject = "X-Service-Project"
)
//SignRequest inject auth related header and sign this request so that this request can access to huawei cloud
type SignRequest func(*http.Request) error
// GetSignFunc sets and initializes the ak/sk auth func
func GetSignFunc(ak, sk, project string) (SignRequest, error) {
s := &hws_cloud.Signer{
AccessKey: ak,
SecretKey: sk,
Service: "",
Region: "",
}
shaAKSKSignFunc, err := GetShaAKSKSignFunc(ak, sk, project)
if err != nil {
return nil, err
}
return func(r *http.Request) error {
if err := shaAKSKSignFunc(r); err != nil {
return err
}
return s.Sign(r)
}, nil
}
// GetShaAKSKSignFunc sets and initializes the ak/sk auth func
func GetShaAKSKSignFunc(ak, sk, project string) (SignRequest, error) {
shaAKSK, err := genShaAKSK(sk, ak)
if err != nil {
return nil, err
}
return func(r *http.Request) error {
if r.Header == nil {
r.Header = make(http.Header)
}
r.Header.Set(HeaderServiceAk, ak)
r.Header.Set(HeaderServiceShaAKSK, shaAKSK)
r.Header.Set(HeaderServiceProject, project)
return nil
}, nil
}
func genShaAKSK(key string, data string) (string, error) {
h := hmac.New(sha256.New, []byte(key))
if _, err := h.Write([]byte(data)); err != nil {
return "", err
}
b := h.Sum(nil)
shaaksk := ""
for _, j := range b {
shaaksk = shaaksk + fmt.Sprintf("%02x", j)
}
return shaaksk, nil
}