55 "crypto/sha1"
66 "encoding/base64"
77 "fmt"
8+ "net/url"
9+ "strconv"
810 "time"
911)
1012
@@ -18,37 +20,42 @@ const (
1820type Header map [string ]string
1921
2022type SignatureContext struct {
21- ConfigServerURL string // 当前访问配置使用的apollo config server的url
22- AccessKey string // 服务启动时缓存的access key
2323 AppID string // appid
24+ AccessKey string // 服务启动时缓存的access key
25+ ConfigServerURL string // 当前访问配置使用的apollo config server的url
2426 RequestURI string // 请求的uri,domain之后的路径
2527 Cluster string // 请求的集群,默认情况下: default,请求GetConfigServers接口时为""
2628}
2729
2830type SignatureFunc func (ctx * SignatureContext ) Header
2931
3032func DefaultSignatureFunc (ctx * SignatureContext ) Header {
31-
32- headers := map [string ]string {}
33- if "" == ctx .AccessKey {
34- return headers
33+ if ctx .AppID == "" || ctx .AccessKey == "" {
34+ return nil
3535 }
3636
37- timestamp := fmt .Sprintf ("%v" , time .Now ().UnixNano ()/ int64 (time .Millisecond ))
38- signature := signature (timestamp , ctx .RequestURI , ctx .AccessKey )
37+ apiURL := fmt .Sprintf ("%s%s" , ctx .ConfigServerURL , ctx .RequestURI )
38+ timestamp := strconv .Itoa (int (time .Now ().UnixMilli ()))
39+ signature := signature (timestamp , getPathWithQuery (apiURL ), ctx .AccessKey )
3940
40- headers [HTTP_HEADER_AUTHORIZATION ] = fmt .Sprintf (AUTHORIZATION_FORMAT , ctx .AppID , signature )
41- headers [HTTP_HEADER_TIMESTAMP ] = timestamp
41+ return map [string ]string {
42+ HTTP_HEADER_AUTHORIZATION : fmt .Sprintf (AUTHORIZATION_FORMAT , ctx .AppID , signature ),
43+ HTTP_HEADER_TIMESTAMP : timestamp ,
44+ }
45+ }
4246
43- return headers
47+ func getPathWithQuery (uri string ) string {
48+ r , err := url .Parse (uri )
49+ if err != nil {
50+ return ""
51+ }
52+ r .Scheme = ""
53+ r .Host = ""
54+ return r .String ()
4455}
4556
4657func signature (timestamp , url , accessKey string ) string {
47-
48- stringToSign := timestamp + DELIMITER + url
49-
50- key := []byte (accessKey )
51- mac := hmac .New (sha1 .New , key )
52- _ , _ = mac .Write ([]byte (stringToSign ))
58+ mac := hmac .New (sha1 .New , []byte (accessKey ))
59+ _ , _ = mac .Write ([]byte (timestamp + DELIMITER + url ))
5360 return base64 .StdEncoding .EncodeToString (mac .Sum (nil ))
5461}
0 commit comments