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 TokenFromRequest helper function #53

Closed
wants to merge 1 commit into from
Closed
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 jwtauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,23 @@ func SetExpiryIn(claims map[string]interface{}, tm time.Duration) {
claims["exp"] = ExpireIn(tm)
}

var tokenRetreivers = []func(r *http.Request) string{
TokenFromHeader,
TokenFromQuery,
}

// TokenFromRequest tries to retreive the token string from all supported methods:
// TokenFromHeader and TokenFromQuery in same order
func TokenFromRequest(r *http.Request) string {
for i := range tokenRetreivers {
if token := tokenRetreivers[i](r); token != "" {
return token
}
}

return ""
}

// TokenFromCookie tries to retreive the token string from a cookie named
// "jwt".
func TokenFromCookie(r *http.Request) string {
Expand Down
41 changes: 41 additions & 0 deletions jwtauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"log"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -231,6 +232,46 @@ func TestMore(t *testing.T) {
}
}

func TestTokenFromRequest(t *testing.T) {
tests := []struct {
desc string
r *http.Request
token string
}{
{
desc: "request does not have any token",
r: &http.Request{URL: &url.URL{}},
},
{
desc: "request has token in header",
r: &http.Request{
Header: http.Header{
"Authorization": []string{"Bearer testtoken"},
},
URL: &url.URL{},
},
token: "testtoken",
},
{
desc: "request has token in query",
r: &http.Request{
URL: &url.URL{
RawQuery: "jwt=testtoken",
},
},
token: "testtoken",
},
}

for _, tt := range tests {
t.Logf("running case: %q", tt.desc)
token := jwtauth.TokenFromRequest(tt.r)
if tt.token != token {
t.Fatalf("expected token: %q, got: %q", tt.token, token)
}
}
}

//
// Test helper functions
//
Expand Down