-
Notifications
You must be signed in to change notification settings - Fork 10
/
signature_checker.go
68 lines (63 loc) · 1.76 KB
/
signature_checker.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
/**
* signature checker as a http middleware
* Rosbit Xu
*/
package wxapi
import (
"github.com/rosbit/go-wx-api/v2/msg"
"net/http"
"strconv"
"time"
"strings"
)
/**
* 创建http处理中间件,验证消息签名,如果非法直接返回错误
* @param wxToken 公众号在微信管理后台定义的token
* @param timeout 消息时间戳超时处理,秒数,如果<=0不检查时间戳
* @param uriPrefixes 需要检查签名的URI前缀列表,不相关的URI忽略检查;如果为nil,全部检查
*/
func NewWxSignatureChecker(wxToken string, timeout int, uriPrefixes []string) func(http.ResponseWriter, *http.Request, http.HandlerFunc) {
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if uriPrefixes != nil {
uri := r.URL.Path
found := false
for _, prefix := range uriPrefixes {
if strings.HasPrefix(uri, prefix) {
found = true
break
}
}
if !found {
next(w, r)
return
}
}
args := make([]string, len(wxmsg.MustSignatureArgs))
query := r.URL.Query()
for i, arg := range wxmsg.MustSignatureArgs {
args[i] = query.Get(arg)
if args[i] == "" {
http.Error(w, "argument expected", http.StatusBadRequest)
return
}
}
if timeout > 0 {
ts, err := strconv.ParseInt(args[wxmsg.TIMESTAMP], 10, 64)
if err != nil {
http.Error(w, "invalid timestamp", http.StatusBadRequest)
return
}
if ts + int64(timeout) < time.Now().Unix() {
http.Error(w, "signature expired", http.StatusBadRequest)
return
}
}
l := []string{wxToken, args[wxmsg.TIMESTAMP], args[wxmsg.NONCE]}
hashcode := wxmsg.HashStrings(l)
if hashcode != args[wxmsg.SIGNATURE] {
http.Error(w, "invalid signanure", http.StatusBadRequest)
return
}
next(w, r)
}
}