Different types for RegisteredClaims before and after JSON marshaling
erudenko opened this issue · comments
Hello dear community.
Here is a sample code that demonstrates the issue:
package main_test
import (
"fmt"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestClaimsMarshalBasic(t *testing.T) {
claims := jwt.RegisteredClaims{
Issuer: "issuer",
Subject: "subject",
Audience: jwt.ClaimStrings{"audience1", "audience2"},
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
ID: "id1",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
fmt.Printf("%+v\n", token)
tokenString, err := token.SigningString()
require.NoError(t, err)
parser := jwt.NewParser()
tokenParsed, _, err := parser.ParseUnverified(tokenString+".faultysignature", &jwt.RegisteredClaims{})
require.NoError(t, err)
assert.IsType(t, token.Claims, tokenParsed.Claims)
}
The issue here is when I create a token with jwt.NewWithClaims
, my claims are of a type of jwt.RegisteredClaims
.
Then I serialise the token to string and parse it with parser.ParseUnverified...
- I got claims of pointer type: *jwt.RegisteredClaims
.
Why is it important? First of all, it is data inconsistency, which is already not good.
The other issue is when I create a custom Claims type with custom fields, and then in the code trying to typecast to my type, I have to know is a pointer or reference behind the Claims interface of my token. Otherwise, the typecast failed.
What is my suggestion? I suggest refactoring jwt.RegisteredClaims to always be a pointer type.