Skip to content

Commit

Permalink
Validate JWT header field (#144)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored Nov 7, 2023
1 parent ea4d746 commit 14ac6af
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
3 changes: 3 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ var (
// ErrUnsupportedAlg indicates that given algorithm is not supported.
ErrUnsupportedAlg = errors.New("algorithm is not supported")

// ErrNotJWTType indicates that JWT token type is not JWT.
ErrNotJWTType = errors.New("token of not JWT type")

// ErrInvalidFormat indicates that token format is not valid.
ErrInvalidFormat = errors.New("token format is not valid")

Expand Down
3 changes: 3 additions & 0 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ func parse(token []byte) (*Token, error) {
header: header,
claims: claims,
}
if !constTimeEqual(tk.header.Type, "JWT") {
return nil, ErrNotJWTType
}
return tk, nil
}

Expand Down
12 changes: 11 additions & 1 deletion parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ func TestParseAnotherAlgorithm(t *testing.T) {
}
}

func TestParseWrongType(t *testing.T) {
tokenHS256 := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkJPTUJPTSJ9.eyJqdGkiOiJqdXN0IGFuIGlkIiwiYXVkIjoiYXVkaWVuY2UifQ.t5oEdZGp0Qbth7lo5fZlV_o4-r9gMoYBSktXbarjWoo`
verifier := mustVerifier(NewVerifierHS(HS256, []byte("key")))

_, err := Parse([]byte(tokenHS256), verifier)
if err == nil {
t.Fatal()
}
}

func TestParseMalformed(t *testing.T) {
f := func(got string) {
t.Helper()
Expand All @@ -81,7 +91,7 @@ func TestParseMalformed(t *testing.T) {
f(`eyJ.xyz`)
f(`eyJ!.x!yz.e30`)
f(`eyJ.xyz.xyz`)
f(`eyJhIjoxMjN9.x!yz.e30`) // `e30` is JSON `{}` in base64
f(`eyJhIjoxMjN9.x!yz.e30`) // `e30` is JSON `{}` in base64.
f(`eyJhIjoxMjN9.e30.x!yz`)
}

Expand Down

0 comments on commit 14ac6af

Please sign in to comment.