...

Source file src/github.com/golang-jwt/jwt/example_test.go

Documentation: github.com/golang-jwt/jwt

     1  package jwt_test
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/golang-jwt/jwt"
     8  )
     9  
    10  // Example (atypical) using the StandardClaims type by itself to parse a token.
    11  // The StandardClaims type is designed to be embedded into your custom types
    12  // to provide standard validation features.  You can use it alone, but there's
    13  // no way to retrieve other fields after parsing.
    14  // See the CustomClaimsType example for intended usage.
    15  func ExampleNewWithClaims_standardClaims() {
    16  	mySigningKey := []byte("AllYourBase")
    17  
    18  	// Create the Claims
    19  	claims := &jwt.StandardClaims{
    20  		ExpiresAt: 15000,
    21  		Issuer:    "test",
    22  	}
    23  
    24  	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    25  	ss, err := token.SignedString(mySigningKey)
    26  	fmt.Printf("%v %v", ss, err)
    27  	//Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 <nil>
    28  }
    29  
    30  // Example creating a token using a custom claims type.  The StandardClaim is embedded
    31  // in the custom type to allow for easy encoding, parsing and validation of standard claims.
    32  func ExampleNewWithClaims_customClaimsType() {
    33  	mySigningKey := []byte("AllYourBase")
    34  
    35  	type MyCustomClaims struct {
    36  		Foo string `json:"foo"`
    37  		jwt.StandardClaims
    38  	}
    39  
    40  	// Create the Claims
    41  	claims := MyCustomClaims{
    42  		"bar",
    43  		jwt.StandardClaims{
    44  			ExpiresAt: 15000,
    45  			Issuer:    "test",
    46  		},
    47  	}
    48  
    49  	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    50  	ss, err := token.SignedString(mySigningKey)
    51  	fmt.Printf("%v %v", ss, err)
    52  	//Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c <nil>
    53  }
    54  
    55  // Example creating a token using a custom claims type.  The StandardClaim is embedded
    56  // in the custom type to allow for easy encoding, parsing and validation of standard claims.
    57  func ExampleParseWithClaims_customClaimsType() {
    58  	tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
    59  
    60  	type MyCustomClaims struct {
    61  		Foo string `json:"foo"`
    62  		jwt.StandardClaims
    63  	}
    64  
    65  	// sample token is expired.  override time so it parses as valid
    66  	at(time.Unix(0, 0), func() {
    67  		token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
    68  			return []byte("AllYourBase"), nil
    69  		})
    70  
    71  		if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
    72  			fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
    73  		} else {
    74  			fmt.Println(err)
    75  		}
    76  	})
    77  
    78  	// Output: bar 15000
    79  }
    80  
    81  // Override time value for tests.  Restore default value after.
    82  func at(t time.Time, f func()) {
    83  	jwt.TimeFunc = func() time.Time {
    84  		return t
    85  	}
    86  	f()
    87  	jwt.TimeFunc = time.Now
    88  }
    89  
    90  // An example of parsing the error types using bitfield checks
    91  func ExampleParse_errorChecking() {
    92  	// Token from another example.  This token is expired
    93  	var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
    94  
    95  	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    96  		return []byte("AllYourBase"), nil
    97  	})
    98  
    99  	if token.Valid {
   100  		fmt.Println("You look nice today")
   101  	} else if ve, ok := err.(*jwt.ValidationError); ok {
   102  		if ve.Errors&jwt.ValidationErrorMalformed != 0 {
   103  			fmt.Println("That's not even a token")
   104  		} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
   105  			// Token is either expired or not active yet
   106  			fmt.Println("Timing is everything")
   107  		} else {
   108  			fmt.Println("Couldn't handle this token:", err)
   109  		}
   110  	} else {
   111  		fmt.Println("Couldn't handle this token:", err)
   112  	}
   113  
   114  	// Output: Timing is everything
   115  }
   116  

View as plain text