Debian Codegraph @

pkg/op/verifier_access_token_example_test.go

raw
1 package op_test
2
3 import (
4 "context"
5 "fmt"
6
7 tu "github.com/zitadel/oidc/v3/internal/testutil"
8 "github.com/zitadel/oidc/v3/pkg/oidc"
9 "github.com/zitadel/oidc/v3/pkg/op"
10 )
11
12 // MyCustomClaims extends the TokenClaims base,
13 // so it implements the oidc.Claims interface.
14 // Instead of carrying a map, we add needed fields// to the struct for type safe access.
15 type MyCustomClaims struct {
16 oidc.TokenClaims
17 NotBefore oidc.Time `json:"nbf,omitempty"`
18 CodeHash string `json:"c_hash,omitempty"`
19 SessionID string `json:"sid,omitempty"`
20 Scopes []string `json:"scope,omitempty"`
21 AccessTokenUseNumber int `json:"at_use_nbr,omitempty"`
22 Foo string `json:"foo,omitempty"`
23 Bar *Nested `json:"bar,omitempty"`
24 }
25
26 // Nested struct types are also possible.
27 type Nested struct {
28 Count int `json:"count,omitempty"`
29 Tags []string `json:"tags,omitempty"`
30 }
31
32 /*
33 accessToken carries the following claims. foo and bar are custom claims
34
35 {
36 "aud": [
37 "unit",
38 "test"
39 ],
40 "bar": {
41 "count": 22,
42 "tags": [
43 "some",
44 "tags"
45 ]
46 },
47 "exp": 4802234675,
48 "foo": "Hello, World!",
49 "iat": 1678097014,
50 "iss": "local.com",
51 "jti": "9876",
52 "nbf": 1678097014,
53 "sub": "[email protected]"
54 }
55 */
56 const accessToken = `eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJhdWQiOlsidW5pdCIsInRlc3QiXSwiYmFyIjp7ImNvdW50IjoyMiwidGFncyI6WyJzb21lIiwidGFncyJdfSwiZXhwIjo0ODAyMjM0Njc1LCJmb28iOiJIZWxsbywgV29ybGQhIiwiaWF0IjoxNjc4MDk3MDE0LCJpc3MiOiJsb2NhbC5jb20iLCJqdGkiOiI5ODc2IiwibmJmIjoxNjc4MDk3MDE0LCJzdWIiOiJ0aW1AbG9jYWwuY29tIn0.OUgk-B7OXjYlYFj-nogqSDJiQE19tPrbzqUHEAjcEiJkaWo6-IpGVfDiGKm-TxjXQsNScxpaY0Pg3XIh1xK6TgtfYtoLQm-5RYw_mXgb9xqZB2VgPs6nNEYFUDM513MOU0EBc0QMyqAEGzW-HiSPAb4ugCvkLtM1yo11Xyy6vksAdZNs_mJDT4X3vFXnr0jk0ugnAW6fTN3_voC0F_9HQUAkmd750OIxkAHxAMvEPQcpbLHenVvX_Q0QMrzClVrxehn5TVMfmkYYg7ocr876Bq9xQGPNHAcrwvVIJqdg5uMUA38L3HC2BEueG6furZGvc7-qDWAT1VR9liM5ieKpPg`
57
58 func ExampleVerifyAccessToken_customClaims() {
59 v := op.NewAccessTokenVerifier("local.com", tu.KeySet{})
60
61 // VerifyAccessToken can be called with the *MyCustomClaims.
62 claims, err := op.VerifyAccessToken[*MyCustomClaims](context.TODO(), accessToken, v)
63 if err != nil {
64 panic(err)
65 }
66
67 // Here we have typesafe access to the custom claims
68 fmt.Println(claims.Foo, claims.Bar.Count, claims.Bar.Tags)
69 // Output: Hello, World! 22 [some tags]
70 }