2014-12-28 23:24:54 +03:00
|
|
|
package jwt_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
2015-07-17 20:28:08 +03:00
|
|
|
|
|
|
|
"github.com/dgrijalva/jwt-go"
|
2014-12-28 23:24:54 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
|
|
|
|
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
return myLookupKey(token.Header["kid"])
|
|
|
|
})
|
|
|
|
|
|
|
|
if err == nil && token.Valid {
|
|
|
|
fmt.Println("Your token is valid. I like your style.")
|
|
|
|
} else {
|
|
|
|
fmt.Println("This token is terrible! I cannot accept this.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-14 08:31:08 +03:00
|
|
|
func ExampleNew(mySigningKey []byte) (string, error) {
|
2014-12-28 23:24:54 +03:00
|
|
|
// Set some claims
|
2015-07-17 20:28:08 +03:00
|
|
|
claim := jwt.MapClaim{
|
|
|
|
"foo": "bar",
|
|
|
|
"exp": time.Now().Add(time.Hour * 72).Unix(),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the token
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
|
|
|
|
|
2014-12-28 23:24:54 +03:00
|
|
|
// Sign and get the complete encoded token as a string
|
|
|
|
tokenString, err := token.SignedString(mySigningKey)
|
|
|
|
return tokenString, err
|
|
|
|
}
|
2014-12-28 23:44:46 +03:00
|
|
|
|
|
|
|
func ExampleParse_errorChecking(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
|
|
|
|
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
return myLookupKey(token.Header["kid"])
|
|
|
|
})
|
|
|
|
|
|
|
|
if token.Valid {
|
|
|
|
fmt.Println("You look nice today")
|
|
|
|
} else if ve, ok := err.(*jwt.ValidationError); ok {
|
|
|
|
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
|
|
|
|
fmt.Println("That's not even a token")
|
|
|
|
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
|
|
|
|
// Token is either expired or not active yet
|
|
|
|
fmt.Println("Timing is everything")
|
|
|
|
} else {
|
|
|
|
fmt.Println("Couldn't handle this token:", err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
fmt.Println("Couldn't handle this token:", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|