forked from storezhang/echox
-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware_signature.go
55 lines (45 loc) · 1.09 KB
/
middleware_signature.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
package echox
import (
`crypto`
`net/http`
`github.com/go-fed/httpsig`
`github.com/labstack/echo/v4`
)
// keySource 获得签名参数
type keySource interface {
// Key 获得签名参数
Key(id string) (key string, err error)
}
// SignatureMiddleware 签名中间件
func SignatureMiddleware(config Signature) MiddlewareFunc {
return func(next handlerFunc) handlerFunc {
return func(ctx *Context) (err error) {
if config.skipper(ctx) {
err = next(ctx)
return
}
req := ctx.Request()
var verifier httpsig.Verifier
if verifier, err = httpsig.NewVerifier(req); nil != err {
return
}
appKey := verifier.KeyId()
var secretKey string
if secretKey, err = config.source.Key(appKey); nil != err {
return
}
key := crypto.PublicKey([]byte(secretKey))
algorithm := httpsig.Algorithm(config.algorithm)
if err = verifier.Verify(key, algorithm); nil != err {
err = &echo.HTTPError{
Code: http.StatusUnauthorized,
Message: "未经允许,禁止驶入!",
Internal: err,
}
} else {
err = next(ctx)
}
return
}
}
}