From 0c245a4f7ecfa253fcd9272dd5ad51d47be7c3b6 Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Tue, 12 Apr 2016 13:33:20 -0700 Subject: [PATCH] added example of parsing using custom type --- example_test.go | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/example_test.go b/example_test.go index dff2855..c1e399c 100644 --- a/example_test.go +++ b/example_test.go @@ -3,6 +3,7 @@ package jwt_test import ( "fmt" "github.com/dgrijalva/jwt-go" + "time" ) // Example (atypical) using the StandardClaims type by itself to parse a token. @@ -25,7 +26,7 @@ func ExampleNewWithClaims_standardClaims() { //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 } -// Example parsing a token using a custom claims type. The StandardClaim is embedded +// Example creating a token using a custom claims type. The StandardClaim is embedded // in the custom type to allow for easy encoding, parsing and validation of standard claims. func ExampleNewWithClaims_customClaimsType() { mySigningKey := []byte("AllYourBase") @@ -50,6 +51,41 @@ func ExampleNewWithClaims_customClaimsType() { //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c } +// Example creating a token using a custom claims type. The StandardClaim is embedded +// in the custom type to allow for easy encoding, parsing and validation of standard claims. +func ExampleParseWithClaims_customClaimsType() { + tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" + + type MyCustomClaims struct { + Foo string `json:"foo"` + jwt.StandardClaims + } + + // sample token is expired. override time so it parses as valid + at(time.Unix(0, 0), func() { + token, err := jwt.ParseWithClaims(tokenString, func(token *jwt.Token) (interface{}, error) { + return []byte("AllYourBase"), nil + }, &MyCustomClaims{}) + + if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { + fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt) + } else { + fmt.Println(err) + } + }) + + // Output: bar 15000 +} + +// Override time value for tests. Restore default value after. +func at(t time.Time, f func()) { + jwt.TimeFunc = func() time.Time { + return t + } + f() + jwt.TimeFunc = time.Now +} + // An example of parsing the error types using bitfield checks func ExampleParse_errorChecking() { // Token from another example. This token is expired