Skip to content

Commit

Permalink
Ignore case-sensitivity for "Bearer"
Browse files Browse the repository at this point in the history
  • Loading branch information
WhyNotHugo committed Aug 19, 2022
1 parent 781c8bd commit d634c29
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
6 changes: 4 additions & 2 deletions request/extractor.go
Expand Up @@ -88,8 +88,10 @@ type BearerExtractor struct{}

func (e BearerExtractor) ExtractToken(req *http.Request) (string, error) {
tokenHeader := req.Header.Get("Authorization")
if tokenHeader == "" || !strings.HasPrefix(tokenHeader, "Bearer ") {
// 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 strings.TrimPrefix(tokenHeader, "Bearer "), nil
return tokenHeader[7:], nil
}
13 changes: 9 additions & 4 deletions request/extractor_test.go
Expand Up @@ -91,16 +91,21 @@ func makeExampleRequest(method, path string, headers map[string]string, urlArgs
}

func TestBearerExtractor(t *testing.T) {
request := makeExampleRequest("POST", "https://example.com/", map[string]string{"Authorization": "Bearer 123"}, nil)
request := makeExampleRequest("POST", "https://example.com/", map[string]string{"Authorization": "Bearer ToKen"}, nil)
token, err := BearerExtractor{}.ExtractToken(request)
if err != nil || token != "123" {
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 123"}, nil)

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)
}
}

0 comments on commit d634c29

Please sign in to comment.