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 1 commit
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
14 changes: 14 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,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{}
WhyNotHugo marked this conversation as resolved.
Show resolved Hide resolved

func (e BearerExtractor) ExtractToken(req *http.Request) (string, error) {
tokenHeader := req.Header.Get("Authorization")
if tokenHeader == "" || !strings.HasPrefix(tokenHeader, "Bearer ") {
oxisto marked this conversation as resolved.
Show resolved Hide resolved
return "", ErrNoTokenInRequest
}
return strings.TrimPrefix(tokenHeader, "Bearer "), nil
oxisto marked this conversation as resolved.
Show resolved Hide resolved
}
15 changes: 15 additions & 0 deletions request/extractor_test.go
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)
}
}