User Tools

Site Tools


jwx.go
/*
 * Author, Copyright: Oleg Borodin <onborodin@gmail.com>
 */
 
package main
 
import (
  "bytes"
  //"crypto/rand"
  //"crypto/rsa"
  "encoding/json"
  "fmt"
  "time"
 
  "github.com/lestrrat-go/jwx/jwa"
  "github.com/lestrrat-go/jwx/jwt"
  //"github.com/lestrrat-go/jwx/jws"
 
)
 
func main() {
 
    token1 := jwt.New()
    token1.Set(jwt.IssuerKey, "Issuer")
    token1.Set(jwt.SubjectKey, "SubjectKey")
    token1.Set(jwt.AudienceKey, "AudienceKey")
    token1.Set(jwt.IssuedAtKey, time.Now())
    token1.Set(jwt.ExpirationKey, time.Now().Add(time.Hour))
    token1.Set("privateClaimKey", "Hello, World!")
 
    json1, err := json.Marshal(token1)
    if err != nil {
        fmt.Printf("error: %s\n", err)
        return
    }
 
    fmt.Printf("%s\n", json1)
 
    sign, err := jwt.Sign(token1, jwa.HS256, []byte("secretword"))
    if err != nil {
        fmt.Printf("error: %s\n", err)
        return
    }
 
    fmt.Println(string(sign))
 
    token2, err := jwt.ParseBytes(sign)
    if err != nil {
        fmt.Printf("error: %s\n", err)
        return
    }
    json2, err := json.Marshal(token2)
    if err != nil {
        fmt.Printf("error: %s\n", err)
        return
    }
    fmt.Printf("%s\n", json2)
 
    fmt.Printf("aud: %s\n", token2.Audience())
    fmt.Printf("sub: %s\n", token2.Subject())
    fmt.Printf("iat: %s\n", token2.IssuedAt().Format(time.RFC3339))
    fmt.Printf("exp: %s\n", token2.Expiration().Format(time.RFC3339))
 
    _, err = jwt.Parse(bytes.NewReader(sign), jwt.WithVerify(jwa.HS256, []byte("secretword")))
    if err != nil {
        fmt.Printf("error: %s\n", err)
        return
    }
}
$ ./jwx
{
    "aud": [
        "AudienceKey"
    ],
    "exp": 1590614165,
    "iat": 1590610565,
    "iss": "Issuer",
    "sub": "SubjectKey",
    "privateClaimKey": "Hello, World!"
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiQXVkaWVuY2VLZXkiXSwiZXhwIjoxNTkwNjE0MTY1LCJpYXQiOjE1OTA2MTA1NjUsImlzcyI6Iklzc3VlciIsInN1YiI6IlN1YmplY3RLZXkiLCJwcml2YXRlQ2xhaW1LZXkiOiJIZWxsbywgV29ybGQhIn0.Ih6ADOL4Q_9G1gFvijtPbtbaH1TZ6b-50NM0I1UmOgo
{
    "aud": [
        "AudienceKey"
    ],
    "exp": 1590614165,
    "iat": 1590610565,
    "iss": "Issuer",
    "sub": "SubjectKey",
    "privateClaimKey": "Hello, World!"
}
aud: [AudienceKey]
sub: SubjectKey
iat: 2020-05-27T20:16:05Z
exp: 2020-05-27T21:16:05Z