Skip to content

Commit

Permalink
Implement a BearerExtractor
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
WhyNotHugo committed Aug 10, 2022
1 parent 9294af5 commit 781c8bd
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
14 changes: 14 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,16 @@ 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")
if tokenHeader == "" || !strings.HasPrefix(tokenHeader, "Bearer ") {
return "", ErrNoTokenInRequest
}
return strings.TrimPrefix(tokenHeader, "Bearer "), nil
}
15 changes: 15 additions & 0 deletions request/extractor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,18 @@ 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 123"}, nil)
token, err := BearerExtractor{}.ExtractToken(request)
if err != nil || token != "123" {
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)

token, err = BearerExtractor{}.ExtractToken(request)
if err == nil || token != "" {
t.Errorf("ExtractToken did not return error, returned: %v, %v", token, err)
}
}

0 comments on commit 781c8bd

Please sign in to comment.