Debian Codegraph @

pkg/client/rp/verifier_tokens_example_test.go

raw
1 package rp_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/client/rp"
9 "github.com/zitadel/oidc/v3/pkg/oidc"
10 )
11
12 // MyCustomClaims extends the TokenClaims base,
13 // so it implements the oidc.Claims interface.
14 // Instead of carrying a map, we add the needed fields to the struct for type-safe access.
15 type MyCustomClaims struct {
16 oidc.TokenClaims
17 NotBefore oidc.Time `json:"nbf,omitempty"`
18 AccessTokenHash string `json:"at_hash,omitempty"`
19 Foo string `json:"foo,omitempty"`
20 Bar *Nested `json:"bar,omitempty"`
21 }
22
23 // GetAccessTokenHash is required to implement
24 // the oidc.IDClaims interface.
25 func (c *MyCustomClaims) GetAccessTokenHash() string {
26 return c.AccessTokenHash
27 }
28
29 // Nested struct types are also possible.
30 type Nested struct {
31 Count int `json:"count,omitempty"`
32 Tags []string `json:"tags,omitempty"`
33 }
34
35 /*
36 idToken carries the following claims. foo and bar are custom claims
37
38 {
39 "acr": "something",
40 "amr": [
41 "foo",
42 "bar"
43 ],
44 "at_hash": "2dzbm_vIxy-7eRtqUIGPPw",
45 "aud": [
46 "unit",
47 "test",
48 "555666"
49 ],
50 "auth_time": 1678100961,
51 "azp": "555666",
52 "bar": {
53 "count": 22,
54 "tags": [
55 "some",
56 "tags"
57 ]
58 },
59 "client_id": "555666",
60 "exp": 4802238682,
61 "foo": "Hello, World!",
62 "iat": 1678101021,
63 "iss": "local.com",
64 "jti": "9876",
65 "nbf": 1678101021,
66 "nonce": "12345",
67 "sub": "[email protected]"
68 }
69 */
70 const idToken = `eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJhY3IiOiJzb21ldGhpbmciLCJhbXIiOlsiZm9vIiwiYmFyIl0sImF0X2hhc2giOiIyZHpibV92SXh5LTdlUnRxVUlHUFB3IiwiYXVkIjpbInVuaXQiLCJ0ZXN0IiwiNTU1Nj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O9lqfIZHGZh-lfAXk27e6FPLlkTDBq8Bx4o4DJ9Fw0hRJGjUTjnYv5cq1vo2-UqldasL6CwTbkzNC_4oQFfRtuodC4Ql7dZ1HRv5LXuYx7KPkOssLZtV9cwtJp5nFzKjcf2zEE_tlbjcpynMwypornRUp1EhCWKRUGkJhJeiP71ECY5pQhShfjBu9Nc5wDpSnZmnk2S4YsPrRK3QkE-iEkas8BfsOCrGoErHjEJexAIDjasGO5PFLWfCA`
72
73 func ExampleVerifyTokens_customClaims() {
74 v := rp.NewIDTokenVerifier("local.com", "555666", tu.KeySet{},
75 rp.WithNonce(func(ctx context.Context) string { return "12345" }),
76 )
77
78 // VerifyAccessToken can be called with the *MyCustomClaims.
79 claims, err := rp.VerifyTokens[*MyCustomClaims](context.TODO(), accessToken, idToken, v)
80 if err != nil {
81 panic(err)
82 }
83 // Here we have typesafe access to the custom claims
84 fmt.Println(claims.Foo, claims.Bar.Count, claims.Bar.Tags)
85 // Output: Hello, World! 22 [some tags]
86 }