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

Implement a BearerExtractor #226

Merged
merged 2 commits into from Aug 19, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions request/extractor.go
Expand Up @@ -3,6 +3,7 @@ package request
import (
"errors"
"net/http"
"strings"
)

// Errors
Expand Down Expand Up @@ -79,3 +80,18 @@ func (e *PostExtractionFilter) ExtractToken(req *http.Request) (string, error) {
return "", err
}
}

// BearerExtractor extracts a token from the Authorization header.
// The header is expected to match the format "Bearer XX", where "XX" is the
// JWT token.
type BearerExtractor struct{}
WhyNotHugo marked this conversation as resolved.
Show resolved Hide resolved

func (e BearerExtractor) ExtractToken(req *http.Request) (string, error) {
tokenHeader := req.Header.Get("Authorization")
// The usual convention is for "Bearer" to be title-cased. However, there's no
// strict rule around this, and it's best to follow the robustness principle here.
if tokenHeader == "" || !strings.HasPrefix(strings.ToLower(tokenHeader), "bearer ") {
return "", ErrNoTokenInRequest
}
return tokenHeader[7:], nil
}
20 changes: 20 additions & 0 deletions request/extractor_test.go
Expand Up @@ -89,3 +89,23 @@ func makeExampleRequest(method, path string, headers map[string]string, urlArgs
}
return r
}

func TestBearerExtractor(t *testing.T) {
request := makeExampleRequest("POST", "https://example.com/", map[string]string{"Authorization": "Bearer ToKen"}, nil)
token, err := BearerExtractor{}.ExtractToken(request)
if err != nil || token != "ToKen" {
t.Errorf("ExtractToken did not return token, returned: %v, %v", token, err)
}

request = makeExampleRequest("POST", "https://example.com/", map[string]string{"Authorization": "Bearo ToKen"}, nil)
token, err = BearerExtractor{}.ExtractToken(request)
if err == nil || token != "" {
t.Errorf("ExtractToken did not return error, returned: %v, %v", token, err)
}

request = makeExampleRequest("POST", "https://example.com/", map[string]string{"Authorization": "BeArEr HeLO"}, nil)
token, err = BearerExtractor{}.ExtractToken(request)
if err != nil || token != "HeLO" {
t.Errorf("ExtractToken did not return token, returned: %v, %v", token, err)
}
}