Skip to content

Commit

Permalink
update examples
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg committed Jan 4, 2020
1 parent 29320d5 commit 128633e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
6 changes: 3 additions & 3 deletions example_build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

func Example_BuildSimple() {
signer := jwt.NewHS256([]byte(`secret`))
signer, _ := jwt.NewHS256([]byte(`secret`))
builder := jwt.NewTokenBuilder(signer)

claims := &jwt.StandardClaims{
Expand Down Expand Up @@ -43,7 +43,7 @@ func (u *userClaims) MarshalBinary() ([]byte, error) {
}

func Example_BuildUserClaims() {
signer := jwt.NewHS256([]byte(`secret`))
signer, _ := jwt.NewHS256([]byte(`secret`))
builder := jwt.NewTokenBuilder(signer)

claims := &userClaims{
Expand Down Expand Up @@ -73,7 +73,7 @@ func (d *dummyClaims) MarshalBinary() ([]byte, error) {
}

func Example_DummyClaims() {
signer := jwt.NewHS256([]byte(`secret`))
signer, _ := jwt.NewHS256([]byte(`secret`))
builder := jwt.NewTokenBuilder(signer)

claims := dummyClaims(map[string]interface{}{
Expand Down
44 changes: 44 additions & 0 deletions example_validate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package jwt_test

import (
"encoding/json"
"fmt"

"github.com/cristalhq/jwt"
)

func Example_Validate() {
t := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`

token, err := jwt.Parse([]byte(t))
if err != nil {
fmt.Printf("parse err: %q", err)
return
}

fmt.Printf("Algorithm %v\n", token.Header().Algorithm)
fmt.Printf("Type %v\n", token.Header().Type)
fmt.Printf("Claims %v\n", string(token.RawClaims()))
fmt.Printf("Payload %v\n", string(token.Payload()))
fmt.Printf("Token %v\n", string(token.Raw()))

claims := &jwt.StandardClaims{}
_ = json.Unmarshal(token.RawClaims(), claims)

validator := jwt.NewValidator(
jwt.AudienceChecker([]string{"admin"}),
jwt.IDChecker("random-unique-string"),
)

err = validator.Validate(claims)
if err != nil {
fmt.Printf("token is invalid: %#v", err)
}

// Output:
// Algorithm HS256
// Type JWT
// Claims {"aud":"admin","jti":"random-unique-string"}
// Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0
// Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs
}

0 comments on commit 128633e

Please sign in to comment.