Skip to content

Commit

Permalink
Implement a BearerExtractor (#226)
Browse files Browse the repository at this point in the history
* Implement a BearerExtractor

This is a rather common extractor; it extracts the JWT from the HTTP
Authorization header, expecting it to include the "Bearer " prefix.

This patterns is rather common and this snippet is repeated in enough
applications that it's probably best to just include it upstream and
allow reusing it.

* Ignore case-sensitivity for "Bearer"
  • Loading branch information
WhyNotHugo authored Aug 19, 2022
1 parent f2878bb commit fdaf0eb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
16 changes: 16 additions & 0 deletions request/extractor.go
Original file line number Diff line number Diff line change
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{}

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
Original file line number Diff line number Diff line change
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)
}
}

0 comments on commit fdaf0eb

Please sign in to comment.