-
Notifications
You must be signed in to change notification settings - Fork 413
Closed
Description
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?
Metadata
Metadata
Assignees
Labels
No labels