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

Question: Why jwt.ParseWithClaims needs to pass a pointer of an anonymous struct ? #430

Closed
niluan304 opened this issue Jan 16, 2025 · 1 comment

Comments

@niluan304
Copy link

niluan304 commented Jan 16, 2025

jwt/example_test.go

Lines 77 to 99 in bc8bdca

// Example creating a token using a custom claims type. The RegisteredClaims is embedded
// in the custom type to allow for easy encoding, parsing and validation of standard claims.
func ExampleParseWithClaims_customClaimsType() {
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA"
type MyCustomClaims struct {
Foo string `json:"foo"`
jwt.RegisteredClaims
}
token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte("AllYourBase"), nil
})
if err != nil {
log.Fatal(err)
} else if claims, ok := token.Claims.(*MyCustomClaims); ok {
fmt.Println(claims.Foo, claims.RegisteredClaims.Issuer)
} else {
log.Fatal("unknown claims type, cannot proceed")
}
// Output: bar test
}

if use pointer of myCustomClaims, can skip type assertion claims, ok := token.Claims.(*MyCustomClaims)

func ExampleParseWithClaims_customClaimsType() {
	tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA"

	type MyCustomClaims struct {
		Foo string `json:"foo"`
		jwt.RegisteredClaims
	}

	var myCustomClaims MyCustomClaims
	token, err := jwt.ParseWithClaims(tokenString, &myCustomClaims, func(token *jwt.Token) (interface{}, error) {
		return []byte("AllYourBase"), nil
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(claims.Foo, claims.RegisteredClaims.Issuer)

	// Output: bar test
}

What is the difference?

@godcong
Copy link

godcong commented Feb 18, 2025

Don't pay too much attention to that.
The only reason to pass this in is for type reflection, since it supports maps and custom structs.
So it must know what this is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants