Skip to content

Commit edfd55b

Browse files
committed
Add Cookie to KeyAuth middleware's KeyLookup
1 parent 58366f9 commit edfd55b

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

middleware/key_auth.go

+15
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package middleware
22

33
import (
44
"errors"
5+
"fmt"
56
"net/http"
67
"strings"
78

@@ -21,6 +22,7 @@ type (
2122
// - "header:<name>"
2223
// - "query:<name>"
2324
// - "form:<name>"
25+
// - "cookie:<name>"
2426
KeyLookup string `yaml:"key_lookup"`
2527

2628
// AuthScheme to be used in the Authorization header.
@@ -91,6 +93,8 @@ func KeyAuthWithConfig(config KeyAuthConfig) echo.MiddlewareFunc {
9193
extractor = keyFromQuery(parts[1])
9294
case "form":
9395
extractor = keyFromForm(parts[1])
96+
case "cookie":
97+
extractor = keyFromCookie(parts[1])
9498
}
9599

96100
return func(next echo.HandlerFunc) echo.HandlerFunc {
@@ -164,3 +168,14 @@ func keyFromForm(param string) keyExtractor {
164168
return key, nil
165169
}
166170
}
171+
172+
// keyFromCookie returns a `keyExtractor` that extracts key from the form.
173+
func keyFromCookie(cookieName string) keyExtractor {
174+
return func(c echo.Context) (string, error) {
175+
key, err := c.Cookie(cookieName)
176+
if err != nil {
177+
return "", fmt.Errorf("missing key in cookies: %w", err)
178+
}
179+
return key.Value, nil
180+
}
181+
}

middleware/key_auth_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,30 @@ func TestKeyAuthWithConfig(t *testing.T) {
157157
expectHandlerCalled: false,
158158
expectError: "code=400, message=missing key in the form",
159159
},
160+
{
161+
name: "ok, custom key lookup, cookie",
162+
givenRequest: func(req *http.Request) {
163+
req.AddCookie(&http.Cookie{
164+
Name: "key",
165+
Value: "valid-key",
166+
})
167+
q := req.URL.Query()
168+
q.Add("key", "valid-key")
169+
req.URL.RawQuery = q.Encode()
170+
},
171+
whenConfig: func(conf *KeyAuthConfig) {
172+
conf.KeyLookup = "cookie:key"
173+
},
174+
expectHandlerCalled: true,
175+
},
176+
{
177+
name: "nok, custom key lookup, missing cookie param",
178+
whenConfig: func(conf *KeyAuthConfig) {
179+
conf.KeyLookup = "cookie:key"
180+
},
181+
expectHandlerCalled: false,
182+
expectError: "code=400, message=missing key in cookies: http: named cookie not present",
183+
},
160184
{
161185
name: "nok, custom errorHandler, error from extractor",
162186
whenConfig: func(conf *KeyAuthConfig) {

0 commit comments

Comments
 (0)