Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add cookie token extractor for v2 #93

Merged
merged 1 commit into from
Jun 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions jwtmiddleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,23 @@ func AuthHeaderTokenExtractor(r *http.Request) (string, error) {
return authHeaderParts[1], nil
}

// CookieTokenExtractor builds a TokenExtractor that takes a request and
// extracts the token from the cookie using the passed in cookieName.
func CookieTokenExtractor(cookieName string) TokenExtractor {
return func(r *http.Request) (string, error) {
cookie, err := r.Cookie(cookieName)
if err != nil {
return "", err
}

if cookie != nil {
return cookie.Value, nil
}

return "", nil // No error, just no JWT
}
}

// ParameterTokenExtractor returns a TokenExtractor that extracts the token
// from the specified query string parameter
func ParameterTokenExtractor(param string) TokenExtractor {
Expand Down
41 changes: 41 additions & 0 deletions jwtmiddleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,47 @@ func Test_AuthHeaderTokenExtractor(t *testing.T) {
}
}

func Test_CookieTokenExtractor(t *testing.T) {
tests := []struct {
name string
cookie *http.Cookie
wantToken string
wantError string
}{
{
name: "no cookie",
wantError: "http: named cookie not present",
},
{
name: "token in cookie",
cookie: &http.Cookie{Name: "token", Value: "i-am-token"},
wantToken: "i-am-token",
},
{
name: "empty cookie",
cookie: &http.Cookie{Name: "token"},
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req, _ := http.NewRequest("GET", "http://example.com", nil)

if tc.cookie != nil {
req.AddCookie(tc.cookie)
}

gotToken, gotError := CookieTokenExtractor("token")(req)
mustErrorMsg(t, tc.wantError, gotError)

if tc.wantToken != gotToken {
t.Fatalf("wanted token: %q, got: %q", tc.wantToken, gotToken)
}

})
}
}

func mustErrorMsg(t testing.TB, want string, got error) {
if (want == "" && got != nil) ||
(want != "" && (got == nil || got.Error() != want)) {
Expand Down