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

A quick way to validate token string #302

Merged
merged 1 commit into from
Jul 20, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,6 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke
// parse Header
var headerBytes []byte
if headerBytes, err = p.DecodeSegment(parts[0]); err != nil {
if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
return token, parts, newError("tokenstring should not contain 'bearer '", ErrTokenMalformed)
}
return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err)
}
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion request/extractor.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ 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 ") {
if len(tokenHeader) < 7 || !strings.HasPrefix(strings.ToLower(tokenHeader[:7]), "bearer ") {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is late and a nitpick, but HasPrefix also slices the front. Is it faster to drop the call completely?

Suggested change
if len(tokenHeader) < 7 || !strings.HasPrefix(strings.ToLower(tokenHeader[:7]), "bearer ") {
if len(tokenHeader) < 7 || strings.ToLower(tokenHeader[:7]) != "bearer " {

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We adjusted it in a follow-up PR: https://github.com/golang-jwt/jwt/pull/329/files

return "", ErrNoTokenInRequest
}
return tokenHeader[7:], nil
Expand Down