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

Different types for RegisteredClaims before and after JSON marshaling #327

Open
Tracked by #335
erudenko opened this issue Jul 25, 2023 · 0 comments
Open
Tracked by #335
Labels
next The next iteration of development, currently `v6`

Comments

@erudenko
Copy link

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.

@oxisto oxisto added the next The next iteration of development, currently `v6` label Aug 14, 2023
@oxisto oxisto mentioned this issue Aug 14, 2023
10 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
next The next iteration of development, currently `v6`
Projects
None yet
Development

No branches or pull requests

2 participants