File: jwt_get_claims_example_test.go

package info (click to toggle)
golang-github-lestrrat-go-jwx 2.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,872 kB
  • sloc: sh: 222; makefile: 86; perl: 62
file content (67 lines) | stat: -rw-r--r-- 1,571 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package examples_test

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/lestrrat-go/jwx/v2/jwt"
)

func Example_jwt_get_claims() {
	tok, err := jwt.NewBuilder().
		IssuedAt(time.Now()).
		Issuer(`github.com/lestrrat-go/jwx`).
		Subject(`example`).
		Claim(`claim1`, `value1`).
		Claim(`claim2`, `2022-05-16T07:35:56+00:00`).
		Build()
	if err != nil {
		fmt.Printf("failed to build token: %s\n", err)
		return
	}

	// Pre-defined fields have typed accessors.
	var _ time.Time = tok.IssuedAt()
	var _ string = tok.Issuer()
	var _ string = tok.Subject()

	var v interface{}
	var ok bool

	// But you can also get them via the generic `.Get()` method.
	// However, v is of type interface{}, so you might need to
	// use a type switch to properly use its value.
	//
	// For the key name you could also use jwt.IssuedAtKey constant
	v, ok = tok.Get(`iat`)

	// Private claims
	v, ok = tok.Get(`claim1`)
	v, ok = tok.Get(`claim2`)

	// However, it is possible to globally specify that a private
	// claim should be parsed into a custom type.
	// In the sample below `claim2` is to be an instance of time.Time
	jwt.RegisterCustomField(`claim2`, time.Time{})

	tok = jwt.New()
	if err := json.Unmarshal([]byte(`{"claim2":"2022-05-16T07:35:56+00:00"}`), tok); err != nil {
		fmt.Printf(`failed to parse token: %s`, err)
		return
	}
	v, ok = tok.Get(`claim2`)
	if !ok {
		fmt.Printf(`failed to get private claim "claim2"`)
		return
	}
	if _, ok := v.(time.Time); !ok {
		fmt.Printf(`claim2 expected to be time.Time, but got %T`, v)
		return
	}

	_ = v
	_ = ok

	// OUTPUT:
}