-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorigin_verifier.go
47 lines (37 loc) · 1.4 KB
/
origin_verifier.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
package middleware
import (
"crypto/subtle"
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
const OriginVerifyHeaderName = "X-Origin-Verify"
// OriginVerifierConfig used to configure the origin authentication middleware.
type OriginVerifierConfig struct {
// Token used to validate requests coming include the required header
Token string
// Skipper defines a function to skip middleware.
Skipper middleware.Skipper
}
// OriginVerifierWithConfig returns a middleware which verifies requests include a `X-Origin-Verify` header
// containing the token configured, requests which fail will be rejected with a 400 bad request status code.
//
// This solution is based on a pattern presented in https://aws.amazon.com/blogs/networking-and-content-delivery/restricting-access-http-api-gateway-lambda-authorizer/
// and uses the same header name.
func OriginVerifierWithConfig(config OriginVerifierConfig) echo.MiddlewareFunc {
if config.Skipper == nil {
config.Skipper = middleware.DefaultSkipper
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if config.Skipper(c) {
return next(c)
}
headerToken := c.Request().Header.Get(OriginVerifyHeaderName)
if subtle.ConstantTimeCompare([]byte(config.Token), []byte(headerToken)) != 1 {
return c.String(http.StatusBadRequest, "Bad Request")
}
return next(c)
}
}
}