Skip to content

Commit

Permalink
Update examples and prepare v3 (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored May 9, 2020
1 parent eebcc12 commit f067e2f
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 50 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ jobs:
runs-on: ubuntu-latest
steps:

- name: Set up Go 1.13
- name: Set up Go 1.14
uses: actions/setup-go@v1
with:
go-version: 1.13
go-version: 1.14
id: go

- name: Check out code
Expand All @@ -25,7 +25,7 @@ jobs:
run: go build .

- name: Test
run: go test -v .
run: go test -v ./...

- name: Generate Coverage
run: go test -coverprofile=coverage.txt
Expand Down
47 changes: 38 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,32 +18,61 @@ JSON Web Tokens for Go
Go version 1.13

```
go get github.com/cristalhq/jwt
go get github.com/cristalhq/jwt/v3
```

## Example

```go
// 1. create a signer & a verifier
key := []byte(`secret`)
signer, errSigner := jwt.NewHS256(key)
builder := jwt.NewBuilder(signer)
signer, err := jwt.NewSignerHS(jwt.HS256, key)
checkErr(err)
verifier, err := jwt.NewVerifierHS(jwt.HS256, key)
checkErr(err)

// 2. create q standard claims
// (you can create your own, see: Example_BuildUserClaims)
claims := &jwt.StandardClaims{
Audience: []string{"admin"},
ID: "random-unique-string",
}
token, errBuild := builder.Build(claims)

raw := token.Raw() // JWT signed token
// 3. create a builder
builder := jwt.NewBuilder(signer)

// 4. and build a token
token, err := builder.Build(claims)

// 5. here is your token :)
var _ []byte = token.Raw() // or just token.String() for string

// 6. parse a token (by example received from a request)
tokenStr := token.String()
newToken, errParse := jwt.ParseString(tokenStr)
checkErr(errParse)

// 7. and verify it's signature
errVerify := verifier.Verify(newToken.Payload(), newToken.Signature())
checkErr(errVerify)

// 8. also you can parse and verify in 1 operation
newToken, err = jwt.ParseAndVerifyString(tokenStr, verifier)
checkErr(err)

// 9. get standard claims
var newClaims jwt.StandardClaims
errClaims := json.Unmarshal(newToken.RawClaims(), &newClaims)
checkErr(errClaims)

errVerify := signer.Verify(token.Payload(), token.Signature())
// 10. see docs for more methods
```

Also see examples: [build](https://github.com/cristalhq/jwt/blob/master/example_build_test.go), [parse](https://github.com/cristalhq/jwt/blob/master/example_parse_test.go).
Also see examples: [this above](https://github.com/cristalhq/jwt/blob/master/example_test.go), [build](https://github.com/cristalhq/jwt/blob/master/example_build_test.go), [parse](https://github.com/cristalhq/jwt/blob/master/example_parse_test.go).

## Documentation

See [these docs](https://godoc.org/github.com/cristalhq/jwt).
See [these docs](https://godoc.org/github.com/cristalhq/jwt/v3).

## License

Expand All @@ -52,7 +81,7 @@ See [these docs](https://godoc.org/github.com/cristalhq/jwt).
[build-img]: https://github.com/cristalhq/jwt/workflows/build/badge.svg
[build-url]: https://github.com/cristalhq/jwt/actions
[doc-img]: https://godoc.org/github.com/cristalhq/jwt?status.svg
[doc-url]: https://godoc.org/github.com/cristalhq/jwt
[doc-url]: https://pkg.go.dev/github.com/cristalhq/jwt/v3
[reportcard-img]: https://goreportcard.com/badge/cristalhq/jwt
[reportcard-url]: https://goreportcard.com/report/cristalhq/jwt
[coverage-img]: https://codecov.io/gh/cristalhq/jwt/branch/master/graph/badge.svg
Expand Down
30 changes: 7 additions & 23 deletions example_build_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package jwt_test

import (
"encoding/json"
"fmt"

"github.com/cristalhq/jwt/v2"
"github.com/cristalhq/jwt/v3"
)

func Example_BuildSimple() {
Expand All @@ -16,10 +15,8 @@ func Example_BuildSimple() {
Audience: []string{"admin"},
ID: "random-unique-string",
}
token, errBuild := builder.Build(claims)
if errBuild != nil {
panic(errBuild)
}
token, err := builder.Build(claims)
checkErr(err)

fmt.Printf("Algorithm %v\n", token.Header().Algorithm)
fmt.Printf("Type %v\n", token.Header().Type)
Expand All @@ -37,15 +34,10 @@ func Example_BuildSimple() {

type userClaims struct {
jwt.StandardClaims

IsAdministrator bool `json:"is_admin"`
Email string `json:"email"`
}

func (u *userClaims) MarshalBinary() ([]byte, error) {
return json.Marshal(u)
}

func Example_BuildUserClaims() {
key := []byte(`secret`)
signer, _ := jwt.NewSignerHS(jwt.HS256, key)
Expand All @@ -59,10 +51,8 @@ func Example_BuildUserClaims() {
IsAdministrator: true,
Email: "foo@bar.baz",
}
token, errBuild := builder.Build(claims)
if errBuild != nil {
panic(errBuild)
}
token, err := builder.Build(claims)
checkErr(err)

fmt.Printf("Claims %v\n", string(token.RawClaims()))
fmt.Printf("Payload %v\n", string(token.Payload()))
Expand All @@ -76,10 +66,6 @@ func Example_BuildUserClaims() {

type dummyClaims map[string]interface{}

func (d *dummyClaims) MarshalBinary() ([]byte, error) {
return json.Marshal(d)
}

func Example_DummyClaims() {
key := []byte(`secret`)
signer, _ := jwt.NewSignerHS(jwt.HS256, key)
Expand All @@ -89,10 +75,8 @@ func Example_DummyClaims() {
"aUdIeNcE": "@everyone",
"well": "well-well-well",
})
token, errBuild := builder.Build(&claims)
if errBuild != nil {
panic(errBuild)
}
token, err := builder.Build(&claims)
checkErr(err)

fmt.Printf("Claims %v\n", string(token.RawClaims()))
fmt.Printf("Payload %v\n", string(token.Payload()))
Expand Down
14 changes: 5 additions & 9 deletions example_parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@ package jwt_test
import (
"fmt"

"github.com/cristalhq/jwt/v2"
"github.com/cristalhq/jwt/v3"
)

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

token, errParse := jwt.Parse([]byte(t))
if errParse != nil {
panic(errParse)
}
token, err := jwt.Parse([]byte(t))
checkErr(err)

fmt.Printf("Algorithm %v\n", token.Header().Algorithm)
fmt.Printf("Type %v\n", token.Header().Type)
Expand All @@ -34,10 +32,8 @@ func Example_ParseAndVerify() {

t := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`

token, errParse := jwt.ParseAndVerify([]byte(t), verifier)
if errParse != nil {
panic(errParse)
}
token, err := jwt.ParseAndVerify([]byte(t), verifier)
checkErr(err)

fmt.Printf("Algorithm %v\n", token.Header().Algorithm)
fmt.Printf("Type %v\n", token.Header().Type)
Expand Down
72 changes: 72 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package jwt_test

import (
"encoding/json"
"fmt"

"github.com/cristalhq/jwt/v3"
)

func Example_JWT() {
// 1. create a signer & a verifier
key := []byte(`secret`)
signer, err := jwt.NewSignerHS(jwt.HS256, key)
checkErr(err)
verifier, err := jwt.NewVerifierHS(jwt.HS256, key)
checkErr(err)

// 2. create q standard claims
// (you can create your own, see: Example_BuildUserClaims)
claims := &jwt.StandardClaims{
Audience: []string{"admin"},
ID: "random-unique-string",
}

// 3. create a builder
builder := jwt.NewBuilder(signer)

// 4. and build a token
token, err := builder.Build(claims)

// 5. here is your token :)
var _ []byte = token.Raw() // or just token.String() for string

// 6. parse a token (by example received from a request)
tokenStr := token.String()
newToken, errParse := jwt.ParseString(tokenStr)
checkErr(errParse)

// 7. and verify it's signature
errVerify := verifier.Verify(newToken.Payload(), newToken.Signature())
checkErr(errVerify)

// 8. also you can parse and verify in 1 operation
newToken, err = jwt.ParseAndVerifyString(tokenStr, verifier)
checkErr(err)

// 9. get standard claims
var newClaims jwt.StandardClaims
errClaims := json.Unmarshal(newToken.RawClaims(), &newClaims)
checkErr(errClaims)

// 10. see docs for more methods

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

// Output:
// Algorithm HS256
// Type JWT
// Claims {"jti":"random-unique-string","aud":"admin"}
// Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0
// Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0.uNaqGEggmy02lZq8FM7KoUKXhOy-zrSF7inYuzIET9o
}

func checkErr(err error) {
if err != nil {
panic(err)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/cristalhq/jwt/v2
module github.com/cristalhq/jwt/v3

go 1.13
2 changes: 1 addition & 1 deletion jwt_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"testing"
"time"

"github.com/cristalhq/jwt/v2"
"github.com/cristalhq/jwt/v3"
)

func BenchmarkAlgEDSA(b *testing.B) {
Expand Down
4 changes: 0 additions & 4 deletions jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ type customClaims struct {
TestField string `json:"test_field"`
}

func (cs *customClaims) MarshalBinary() (data []byte, err error) {
return json.Marshal(cs)
}

func TestMarshalHeader(t *testing.T) {
f := func(h *Header, want string) {
t.Helper()
Expand Down

0 comments on commit f067e2f

Please sign in to comment.