# Working with JWK

In this document we describe how to work with JWK using `github.com/lestrrat-go/jwx/v3/jwk`

* [Terminology](#terminology)
  * [JWK / Key](#jwk--key)
  * [JWK Set / Set](#jwk-set--set)
  * [Raw Key](#raw-key)
* [Parsing](#parsing)
  * [Parse a set](#parse-a-set)
  * [Parse a key](#parse-a-key)
  * [Parse a key or set in PEM format](#parse-a-key-or-a-set-in-pem-format)
  * [Parse a key from a file](#parse-a-key-from-a-file)
  * [Parse a key as a struct field](#parse-a-key-as-a-struct-field)
* [Construction](#construction)
  * [Using jwk.Import()](#using-jwkfromraw)
* [Fetching JWK Sets](#fetching-jwk-sets)
  * [Parse a key from a remote resource](#parse-a-key-from-a-remote-resource)
  * [Auto-refreshing remote keys](#auto-refreshing-remote-keys)
  * [Default Fetch Security Behavior](#default-fetch-security-behavior)
  * [Using Whitelists](#using-whitelists)
* [Working with jwk.Key](#working-with-jwkkey)
  * [Working with key-specific methods](#working-with-key-specific-methods)
  * [Setting values to fields](#setting-values-to-fields)
  * [Converting a jwk.Key to a raw key](#converting-a-jwkkey-to-a-raw-key)
  * [Filtering Keys with KeyFilter](#filtering-keys-with-keyfilter)

---

# Terminology

## JWK / Key

Used to describe a JWK key, possibly of type RSA, ECDSA, OKP, or Symmetric.

## JWK Set / Set

A "jwk" resource on the web can either contain a single JWK or an array of multiple JWKs.
The latter is called a JWK Set.

It is impossible to know what the resource contains beforehand, so functions like [`jwk.Parse()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Parse)
and [`jwk.ReadFile()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#ReadFile) returns a [`jwk.Set`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Set) by default.

## Raw Key

Used to describe the underlying raw key that a JWK represents. For example, an RSA JWK can
represent rsa.PrivateKey/rsa.PublicKey, ECDSA JWK can represent ecdsa.PrivateKey/ecdsa.PublicKey,
and so forth.

---

The table below shows the matrix of key types and their respective `jwk.Key` and "raw" types.
If given anything else, `jwk.Import` will return an error.

|           | `jwk.Key` Type                               | Raw Key Type                              |
|-----------|----------------------------------------------|-------------------------------------------|
| RSA       | `jwk.RSAPublicKey` / `jwk.RSAPrivateKey`     | `*rsa.PublicKey` / `*rsa.PublicKey`       |
| ECDSA     | `jwk.ECDSAPublicKey` / `jwk.ECDSAPrivateKey` | `*ecdsa.PublicKey` / `*ecdsa.PublicKey`   |
| OKP       | `jwk.OKPPublicKey` / `jwk.OKPPrivateKey`     | `ed25519.PublicKey` / `ed25519.PublicKey` |
| Symmetric | `jwk.SymmetricKey`                           | []byte                                    |

# Parsing

## Parse a set

If you have a key set, or are unsure if the source is a set or a single key, you should use [`jwk.Parse()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Parse)

<!-- INCLUDE(examples/jwk_parse_jwks_example_test.go) -->
```go
package examples_test

import (
  "encoding/json"
  "fmt"
  "os"

  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_parse_jwks() {
  const src = `{
    "keys": [
      {"kty":"EC",
       "crv":"P-256",
       "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
       "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
       "use":"enc",
       "kid":"1"},
      {"kty":"RSA",
       "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
       "e":"AQAB",
       "alg":"RS256",
       "kid":"2011-04-29"}
    ]
  }`

  set, err := jwk.Parse([]byte(src))
  if err != nil {
    fmt.Printf("failed to parse JWKS: %s\n", err)
    return
  }

  json.NewEncoder(os.Stdout).Encode(set)
  // OUTPUT:
  // {"keys":[{"crv":"P-256","kid":"1","kty":"EC","use":"enc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"},{"alg":"RS256","e":"AQAB","kid":"2011-04-29","kty":"RSA","n":"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"}]}
}
```
source: [examples/jwk_parse_jwks_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_parse_jwks_example_test.go)
<!-- END INCLUDE -->

## Unsupported keys in a set

Per RFC 7517 §5, an implementation SHOULD ignore keys within a JWK Set whose
key type is not understood, that are missing required members, or whose values
are out of the supported range. A single such entry — for example a
post-quantum key published by an identity provider alongside classical RSA/EC
keys — should not have to prevent you from using every key you *do* understand.

This is no longer hypothetical. As post-quantum cryptography is deployed,
identity providers are expected to publish JWK Sets that mix classical RSA/EC
keys with PQC key types (for example `AKP`, used by ML-DSA) that a v3 build
does not understand. A JWKS that parses cleanly today can gain an entry v3
cannot decode the moment the provider rotates in a PQC key.

By default v3 stays fail-fast: the first entry in a `"keys"` array that cannot
be parsed fails the whole set. This is unchanged from earlier v3 releases, so
existing callers see no difference. `jwk.Parse` offers three modes for an
entry that cannot be parsed:

| Mode | Behavior | How to select |
|------|----------|---------------|
| Strict (default) | The first unparseable entry fails the whole set | (no option) |
| Retain | The entry is kept in the set as a `jwk.UnsupportedKey` placeholder | `jwk.WithStrictKeySetParsing(false)` |
| Drop | The entry is discarded | `jwk.WithIgnoreParseError(true)` — takes precedence regardless of the strict setting |

**If you consume third-party JWK Sets, opt into retain.** Unlike v4 (which
retains by default), v3's default is fail-fast — safe for JWK Sets you control,
but a liability for a set published by someone else. Under the default, the
first entry your build cannot parse — a PQC key your provider rotates in, say —
fails the whole set, and you lose the classical keys you could still have used.
When you parse a JWKS from a provider that may add key types this build does not
understand, pass `jwk.WithStrictKeySetParsing(false)` (or set it process-wide
via `jwk.Configure`) so the unknown entry is retained as an inspectable
`jwk.UnsupportedKey` placeholder instead of breaking the parse.

In retain mode the set parses successfully and `Set.Len()` / iteration include
the placeholder. A `jwk.UnsupportedKey` preserves the entry's original JSON, so
a set that contains one round-trips losslessly (a fetch + re-serialize does not
strip keys you did not understand), and `json.Marshal` of the placeholder itself
reproduces the original entry. Check for a placeholder with
`jwk.IsUnsupportedKey`; type-assert to `jwk.UnsupportedKey` when you also need
`Reason()`:

```go
set, err := jwk.Parse(src, jwk.WithStrictKeySetParsing(false))
if err != nil {
  // ... handle error
}
for i := 0; i < set.Len(); i++ {
  key, _ := set.Key(i)
  if jwk.IsUnsupportedKey(key) {
    // This entry is not supported by this build. Type-assert to
    // jwk.UnsupportedKey to inspect it: Reason() explains why it could
    // not be parsed (an extension module may be required), and
    // json.Marshal(key) reproduces the original entry's JSON.
    continue
  }
  // ... use the supported key
}
```

A placeholder cannot be used for any cryptographic operation: `Thumbprint`,
`PublicKey`, and `Validate` return an error, and key-selection paths in `jws`
and `jwe` reject it with a descriptive per-key error (naming the `kid`, the raw
`kty`, and the underlying reason) rather than aborting the whole verify/decrypt.
`jwk.PublicSetOf` also errors when the input set contains a placeholder, because
there is no way to prove the unparseable entry holds no private material; pass
`jwk.WithOmitUnsupportedKeys(true)` to drop placeholders from the output set
instead.

`jwk.WithStrictKeySetParsing` can also be passed to `jwk.Configure()` to change
the default process-wide. Note that retention applies only to sets:
`jwk.ParseKey` (and a bare single JWK passed to `jwk.Parse`) always returns a
hard error for an unparseable key, regardless of this option.

Calling `Set.UnmarshalJSON` directly (for example via `json.Unmarshal`) takes
no per-call options: strict vs. retain follows the global setting from
`jwk.Configure`. Drop mode has no per-call option there either —
`jwk.WithIgnoreParseError` is a `jwk.Parse` option, and there is no
`jwk.Configure` equivalent for it.

The pre-existing `jwk.WithIgnoreParseError(true)` remedy still drops unparseable
entries silently; retention differs in that it *keeps* them as inspectable
placeholders instead of discarding them.

Cross-version note: v4 defaults to retain (false), while v3 defaults to strict
(true). The option means the same thing in both — only the default differs — so
call sites that pass it explicitly are source-compatible across the v3→v4
migration.

## Parse a key

If you are sure that the source only contains a single key, you can use [`jwk.ParseKey()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#ParseKey)

<!-- INCLUDE(examples/jwk_parse_key_example_test.go) -->
```go
package examples_test

import (
  "encoding/json"
  "fmt"
  "os"

  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_parse_key() {
  const src = `{
    "kty":"EC",
    "crv":"P-256",
    "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
    "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
    "use":"enc",
    "kid":"1"
  }`

  key, err := jwk.ParseKey([]byte(src))
  if err != nil {
    fmt.Printf("failed parse key: %s\n", err)
    return
  }

  json.NewEncoder(os.Stdout).Encode(key)
  // OUTPUT:
  // {"crv":"P-256","kid":"1","kty":"EC","use":"enc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"}
}
```
source: [examples/jwk_parse_key_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_parse_key_example_test.go)
<!-- END INCLUDE -->

## Parse a key or a set in PEM format

Sometimes keys come in ASN.1 DER PEM format.  To parse these files, use the [`jwk.WithPEM()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#WithPEM) option.

<!-- INCLUDE(examples/jwk_parse_with_pem_example_test.go) -->
```go
package examples_test

import (
  "fmt"
  "os"

  "github.com/lestrrat-go/jwx/v3/internal/json"
  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_parse_with_pem() {
  const src = `-----BEGIN CERTIFICATE-----
MIIEljCCAn4CCQCTQBoGDvUbQTANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJK
UDAeFw0yMTA0MDEwMDE4MjhaFw0yMjA0MDEwMDE4MjhaMA0xCzAJBgNVBAYTAkpQ
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvws4H/OxVS3CW1zvUgjs
H443df9zCAblLVPPdeRD11Jl1OZmGS7rtQNjQyT5xGpeuk77ZJcfDNLx+mSEtiYQ
V37GD5MPz+RX3hP2azuLvxoBseaHE6kC8tkDed8buQLl1hgms15KmKnt7E8B+EK2
1YRj0w6ZzehIllTbbj6gDJ39kZ2VHdLf5+4W0Kyh9cM4aA0si2jQJQsohW2rpt89
b+IagFau+sxP3GFUjSEvyXIamXhS0NLWuAW9UvY/RwhnIo5BzmWZd/y2R305T+QT
rHtb/8aGav8mP3uDx6AMDp/0UMKFUO4mpoOusMnrplUPS4Lz6RNpffmrrglOEuRZ
/eSFzGL35OeL12aYSyrbFIVsc/aLs6MkoplsuSG6Zhx345h/dA2a8Ub5khr6bksP
zGLer+bpBrQQsy21unvCIUz5y7uaYhV3Ql+aIZ+dwpEgZ3xxAvdKKeoCGQlhH/4J
0sSuutUtuTLfrBSgLHJEv2HIzeynChL2CYR8aku/nL68VTdmSt9UY2JGMOf9U8BI
fGRpkWBvI8hddMxNm8wF+09WScaZ2JWu7qW/l2jOdgesPIWRg+Hm3NaRSHqAWCOq
VUJk9WkCAye0FPALqSvH0ApDKxNtGZb5JZRCW19TqmhgXbAqIf5hsxDaGIXZcW9S
CqapZPw7Ccs7BOKSFvmM9p0CAwEAATANBgkqhkiG9w0BAQsFAAOCAgEAVfLzKRdA
0vFpAAp3K+CDth7mag2WWFOXjlWZ+4pxfEBX3k7erJbj6+qYuCvCHXqIZnK1kZzD
p4zwsu8t8RfSmPvxcm/jkvecG4DAIGTdhBVtAf/9PU3e4kZFQCqizicQABh+ZFKV
dDtkRebUA5EAvP8E/OrvrjYU5xnOxOZU3arVXJfKFjVD619qLuF8XXW5700Gdqwn
wBgasTCCg9+tniiscKaET1m9C4PdrlXuAIscV9tGcJ7yEAao1BXokyJ+mK6K2Zv1
z/vvUJA/rGMBJoUjnWrRHON1JMNou2KyRO6z37GpRnfPiNgFpGv2x3ZNeix7H4bP
6+x4KZWQir5047p9hV4YrqMXeULEj3uG2GnOgdR7+hiN39arFVr11DMgABmx19SM
VQpTHrC8a605wwCBWnkiYdNojLa5WgeEHdBghKVpWnx9frYgZcz2UP861el5Lg9R
j04wkGL4IORYiM7VHSHNU4u/dlgfQE1y0T+1CzXwquy4csvbBzBKnZ1o9ZBsOtWS
ox0RaBsMD70mvTwKKmlCSD5HgZZTC0CfGWk4dQp/Mct5Z0x0HJMEJCJzpgTn3CRX
z8CjezfckLs7UKJOlhu3OU9TFsiGDzSDBZdDWO1/uciJ/AAWeSmsBt8cKL0MirIr
c4wOvhbalcX0FqTM3mXCgMFRbibquhwdxbU=
-----END CERTIFICATE-----`

  key, err := jwk.ParseKey([]byte(src), jwk.WithPEM(true))
  if err != nil {
    fmt.Printf("failed to parse key in PEM format: %s\n", err)
    return
  }

  json.NewEncoder(os.Stdout).Encode(key)
  // OUTPUT:
  // {"e":"AQAB","kty":"RSA","n":"vws4H_OxVS3CW1zvUgjsH443df9zCAblLVPPdeRD11Jl1OZmGS7rtQNjQyT5xGpeuk77ZJcfDNLx-mSEtiYQV37GD5MPz-RX3hP2azuLvxoBseaHE6kC8tkDed8buQLl1hgms15KmKnt7E8B-EK21YRj0w6ZzehIllTbbj6gDJ39kZ2VHdLf5-4W0Kyh9cM4aA0si2jQJQsohW2rpt89b-IagFau-sxP3GFUjSEvyXIamXhS0NLWuAW9UvY_RwhnIo5BzmWZd_y2R305T-QTrHtb_8aGav8mP3uDx6AMDp_0UMKFUO4mpoOusMnrplUPS4Lz6RNpffmrrglOEuRZ_eSFzGL35OeL12aYSyrbFIVsc_aLs6MkoplsuSG6Zhx345h_dA2a8Ub5khr6bksPzGLer-bpBrQQsy21unvCIUz5y7uaYhV3Ql-aIZ-dwpEgZ3xxAvdKKeoCGQlhH_4J0sSuutUtuTLfrBSgLHJEv2HIzeynChL2CYR8aku_nL68VTdmSt9UY2JGMOf9U8BIfGRpkWBvI8hddMxNm8wF-09WScaZ2JWu7qW_l2jOdgesPIWRg-Hm3NaRSHqAWCOqVUJk9WkCAye0FPALqSvH0ApDKxNtGZb5JZRCW19TqmhgXbAqIf5hsxDaGIXZcW9SCqapZPw7Ccs7BOKSFvmM9p0"}
}
```
source: [examples/jwk_parse_with_pem_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_parse_with_pem_example_test.go)
<!-- END INCLUDE -->

## Parse a key from a file

To parse keys stored in a file, [`jwk.ReadFile()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#ReadFile) can be used. 

<!-- INCLUDE(examples/jwk_readfile_example_test.go) -->
```go
package examples_test

import (
  "encoding/json"
  "fmt"
  "os"

  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_readfile() {
  const src = `{
    "keys": [
      {"kty":"EC",
       "crv":"P-256",
       "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
       "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
       "use":"enc",
       "kid":"1"},
      {"kty":"RSA",
       "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
       "e":"AQAB",
       "alg":"RS256",
       "kid":"2011-04-29"}
    ]
  }`

  f, err := os.CreateTemp(``, `jwk_readfile-*.jwk`)
  if err != nil {
    fmt.Printf("failed to create temporary file: %s\n", err)
    return
  }
  defer os.Remove(f.Name())

  fmt.Fprint(f, src)
  f.Close()

  key, err := jwk.ReadFile(f.Name())
  if err != nil {
    fmt.Printf("failed to parse key: %s\n", err)
    return
  }

  json.NewEncoder(os.Stdout).Encode(key)

  // OUTPUT:
  // {"keys":[{"crv":"P-256","kid":"1","kty":"EC","use":"enc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"},{"alg":"RS256","e":"AQAB","kid":"2011-04-29","kty":"RSA","n":"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"}]}
}
```
source: [examples/jwk_readfile_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_readfile_example_test.go)
<!-- END INCLUDE -->

`jwk.ReadFile()` accepts the same options as [`jwk.Parse()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Parse), therefore you can read a PEM-encoded file via the following incantation:

<!-- INCLUDE(examples/jwk_readfile_with_pem_example_test.go) -->
```go
package examples_test

import (
  "fmt"
  "os"

  "github.com/lestrrat-go/jwx/v3/internal/json"
  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_readfile_with_pem() {
  const src = `-----BEGIN CERTIFICATE-----
MIIEljCCAn4CCQCTQBoGDvUbQTANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJK
UDAeFw0yMTA0MDEwMDE4MjhaFw0yMjA0MDEwMDE4MjhaMA0xCzAJBgNVBAYTAkpQ
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvws4H/OxVS3CW1zvUgjs
H443df9zCAblLVPPdeRD11Jl1OZmGS7rtQNjQyT5xGpeuk77ZJcfDNLx+mSEtiYQ
V37GD5MPz+RX3hP2azuLvxoBseaHE6kC8tkDed8buQLl1hgms15KmKnt7E8B+EK2
1YRj0w6ZzehIllTbbj6gDJ39kZ2VHdLf5+4W0Kyh9cM4aA0si2jQJQsohW2rpt89
b+IagFau+sxP3GFUjSEvyXIamXhS0NLWuAW9UvY/RwhnIo5BzmWZd/y2R305T+QT
rHtb/8aGav8mP3uDx6AMDp/0UMKFUO4mpoOusMnrplUPS4Lz6RNpffmrrglOEuRZ
/eSFzGL35OeL12aYSyrbFIVsc/aLs6MkoplsuSG6Zhx345h/dA2a8Ub5khr6bksP
zGLer+bpBrQQsy21unvCIUz5y7uaYhV3Ql+aIZ+dwpEgZ3xxAvdKKeoCGQlhH/4J
0sSuutUtuTLfrBSgLHJEv2HIzeynChL2CYR8aku/nL68VTdmSt9UY2JGMOf9U8BI
fGRpkWBvI8hddMxNm8wF+09WScaZ2JWu7qW/l2jOdgesPIWRg+Hm3NaRSHqAWCOq
VUJk9WkCAye0FPALqSvH0ApDKxNtGZb5JZRCW19TqmhgXbAqIf5hsxDaGIXZcW9S
CqapZPw7Ccs7BOKSFvmM9p0CAwEAATANBgkqhkiG9w0BAQsFAAOCAgEAVfLzKRdA
0vFpAAp3K+CDth7mag2WWFOXjlWZ+4pxfEBX3k7erJbj6+qYuCvCHXqIZnK1kZzD
p4zwsu8t8RfSmPvxcm/jkvecG4DAIGTdhBVtAf/9PU3e4kZFQCqizicQABh+ZFKV
dDtkRebUA5EAvP8E/OrvrjYU5xnOxOZU3arVXJfKFjVD619qLuF8XXW5700Gdqwn
wBgasTCCg9+tniiscKaET1m9C4PdrlXuAIscV9tGcJ7yEAao1BXokyJ+mK6K2Zv1
z/vvUJA/rGMBJoUjnWrRHON1JMNou2KyRO6z37GpRnfPiNgFpGv2x3ZNeix7H4bP
6+x4KZWQir5047p9hV4YrqMXeULEj3uG2GnOgdR7+hiN39arFVr11DMgABmx19SM
VQpTHrC8a605wwCBWnkiYdNojLa5WgeEHdBghKVpWnx9frYgZcz2UP861el5Lg9R
j04wkGL4IORYiM7VHSHNU4u/dlgfQE1y0T+1CzXwquy4csvbBzBKnZ1o9ZBsOtWS
ox0RaBsMD70mvTwKKmlCSD5HgZZTC0CfGWk4dQp/Mct5Z0x0HJMEJCJzpgTn3CRX
z8CjezfckLs7UKJOlhu3OU9TFsiGDzSDBZdDWO1/uciJ/AAWeSmsBt8cKL0MirIr
c4wOvhbalcX0FqTM3mXCgMFRbibquhwdxbU=
-----END CERTIFICATE-----`

  f, err := os.CreateTemp(``, `jwk_readfile_with_pem-*.jwk`)
  if err != nil {
    fmt.Printf("failed to create temporary file: %s\n", err)
    return
  }
  defer os.Remove(f.Name())

  fmt.Fprint(f, src)
  f.Close()

  key, err := jwk.ReadFile(f.Name(), jwk.WithPEM(true))
  if err != nil {
    fmt.Printf("failed to parse key in PEM format: %s\n", err)
    return
  }

  json.NewEncoder(os.Stdout).Encode(key)
  // OUTPUT:
  // {"keys":[{"e":"AQAB","kty":"RSA","n":"vws4H_OxVS3CW1zvUgjsH443df9zCAblLVPPdeRD11Jl1OZmGS7rtQNjQyT5xGpeuk77ZJcfDNLx-mSEtiYQV37GD5MPz-RX3hP2azuLvxoBseaHE6kC8tkDed8buQLl1hgms15KmKnt7E8B-EK21YRj0w6ZzehIllTbbj6gDJ39kZ2VHdLf5-4W0Kyh9cM4aA0si2jQJQsohW2rpt89b-IagFau-sxP3GFUjSEvyXIamXhS0NLWuAW9UvY_RwhnIo5BzmWZd_y2R305T-QTrHtb_8aGav8mP3uDx6AMDp_0UMKFUO4mpoOusMnrplUPS4Lz6RNpffmrrglOEuRZ_eSFzGL35OeL12aYSyrbFIVsc_aLs6MkoplsuSG6Zhx345h_dA2a8Ub5khr6bksPzGLer-bpBrQQsy21unvCIUz5y7uaYhV3Ql-aIZ-dwpEgZ3xxAvdKKeoCGQlhH_4J0sSuutUtuTLfrBSgLHJEv2HIzeynChL2CYR8aku_nL68VTdmSt9UY2JGMOf9U8BIfGRpkWBvI8hddMxNm8wF-09WScaZ2JWu7qW_l2jOdgesPIWRg-Hm3NaRSHqAWCOqVUJk9WkCAye0FPALqSvH0ApDKxNtGZb5JZRCW19TqmhgXbAqIf5hsxDaGIXZcW9SCqapZPw7Ccs7BOKSFvmM9p0"}]}
}
```
source: [examples/jwk_readfile_with_pem_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_readfile_with_pem_example_test.go)
<!-- END INCLUDE -->

## Parse a key as a struct field

As `jwk.Key` is an interface, it can't directly be used as an argument in `json.Unmarshal`.
For example, the following would fail:

```go
var key jwk.Key
json.Unmarshal(data, &key) // error
```

This poses a problem when you want to use `jwk.Key` as a struct field in another struct
that needs to handle `json.Unmarshal`. To overcome this, you can either define a custom
`UnmarshalJSON([]byte) error` for your container struct, or you can use a "proxy" struct
that will intercept the field holding the `jwk.Key`.

<!-- INCLUDE(examples/jwk_struct_field_example_test.go) -->
```go
package examples_test

import (
  "encoding/json"
  "fmt"
  "os"

  "github.com/lestrrat-go/jwx/v3/jwk"
)

type Container struct {
  Key jwk.Key `json:"key"`
}

// This is only one way to parse a struct field whose dynamic
// type is unknown at compile time. In this example we use
// a proxy/wrapper to trick `Container` from attempting to
// parse the `.Key` field, and intercept the value that
// would have gone into the `Container` struct into
// `Proxy` struct's `.Key` struct field
type Proxy struct {
  Container
  Key json.RawMessage `json:"key"`
}

func Example_jwk_struct_field() {
  const src = `{
    "key": {
      "kty":"EC",
      "crv":"P-256",
      "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
      "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
      "use":"enc",
      "kid":"1"
    }
  }`

  var p Proxy
  if err := json.Unmarshal([]byte(src), &p); err != nil {
    fmt.Printf("failed to unmarshal from JSON: %s\n", err)
    return
  }

  // Parse the intercepted `Proxy.Key` as a `jwk.Key`
  // and assign it to `Container.Key`
  key, err := jwk.ParseKey(p.Key)
  if err != nil {
    fmt.Printf("failed to parse key: %s\n", err)
    return
  }
  p.Container.Key = key

  json.NewEncoder(os.Stdout).Encode(p.Container)
  // OUTPUT:
  // {"key":{"crv":"P-256","kid":"1","kty":"EC","use":"enc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"}}
}
```
source: [examples/jwk_struct_field_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_struct_field_example_test.go)
<!-- END INCLUDE -->

# Construction

## Using jwk.Import()

Users can create a new key from scratch using [`jwk.Import()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Import).

[`jwk.Import()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Import) requires the raw key as its argument.
There are other ways to creating keys from a raw key, but they require knowing its type in advance.
Use [`jwk.Import()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Import) when you have a key type which you do not know its underlying type in advance.

It automatically creates the appropriate underlying key based on the given argument type.

| Argument Type | Key Type | Note |
|---------------|----------|------|
| []byte        | Symmetric Key | |
| ecdsa.PrivateKey | ECDSA Private Key | Argument may also be a pointer |
| ecdsa.PubliKey | ECDSA Public Key | Argument may also be a pointer |
| rsa.PrivateKey | RSA Private Key | Argument may also be a pointer |
| rsa.PubliKey | RSA Public Key | Argument may also be a pointer |
| x25519.PrivateKey | OKP Private Key | |
| x25519.PubliKey | OKP Public Key | |

<!-- INCLUDE(examples/jwk_import_example_test.go) -->
```go
package examples_test

import (
  "crypto/ecdsa"
  "crypto/elliptic"
  "crypto/rand"
  "crypto/rsa"
  "fmt"

  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_import() {
  // First, THIS IS THE WRONG WAY TO USE jwk.Import().
  //
  // Assume that the file contains a JWK in JSON format
  //
  //  buf, _ := os.ReadFile(file)
  //  key, _ := jwk.Import(buf)
  //
  // This is not right, because the jwk.Import() function determines
  // the type of `jwk.Key` to create based on the TYPE of the argument.
  // In this case the type of `buf` is always []byte, and therefore
  // it will always create a symmetric key.
  //
  // What you want to do is to _parse_ `buf`.
  //
  //  keyset, _ := jwk.Parse(buf)
  //  key, _    := jwk.ParseKey(buf)
  //
  // See other examples in examples/jwk_parse_key_example_test.go and
  // examples/jwk_parse_jwks_example_test.go

  // []byte -> jwk.SymmetricKey
  {
    raw := []byte("Lorem Ipsum")
    key, err := jwk.Import(raw)
    if err != nil {
      fmt.Printf("failed to create symmetric key: %s\n", err)
      return
    }
    if _, ok := key.(jwk.SymmetricKey); !ok {
      fmt.Printf("expected jwk.SymmetricKey, got %T\n", key)
      return
    }
  }

  // *rsa.PrivateKey -> jwk.RSAPrivateKey
  // *rsa.PublicKey  -> jwk.RSAPublicKey
  {
    raw, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
      fmt.Printf("failed to generate new RSA private key: %s\n", err)
      return
    }

    key, err := jwk.Import(raw)
    if err != nil {
      fmt.Printf("failed to create symmetric key: %s\n", err)
      return
    }
    if _, ok := key.(jwk.RSAPrivateKey); !ok {
      fmt.Printf("expected jwk.SymmetricKey, got %T\n", key)
      return
    }
    // PublicKey is omitted for brevity
  }

  // *ecdsa.PrivateKey -> jwk.ECDSAPrivateKey
  // *ecdsa.PublicKey  -> jwk.ECDSAPublicKey
  {
    raw, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
    if err != nil {
      fmt.Printf("failed to generate new ECDSA private key: %s\n", err)
      return
    }

    key, err := jwk.Import(raw)
    if err != nil {
      fmt.Printf("failed to create symmetric key: %s\n", err)
      return
    }
    if _, ok := key.(jwk.ECDSAPrivateKey); !ok {
      fmt.Printf("expected jwk.SymmetricKey, got %T\n", key)
      return
    }
    // PublicKey is omitted for brevity
  }

  // OUTPUT:
}
```
source: [examples/jwk_import_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_import_example_test.go)
<!-- END INCLUDE -->

> Warning: `jwk.Import([]byte(...))` only requires a non-empty octet string. When the key is used with a specific algorithm, size it yourself: use at least 32/48/64 bytes for `HS256`/`HS384`/`HS512`; 16/24/32 bytes for `A128KW`/`A192KW`/`A256KW`, `A128GCM`/`A192GCM`/`A256GCM`, and `A128GCMKW`/`A192GCMKW`/`A256GCMKW`; and 32/48/64 bytes for `A128CBC-HS256`/`A192CBC-HS384`/`A256CBC-HS512`.

# Fetching JWK Sets

## Parse a key from a remote resource

To parse keys stored in a remote location pointed by a HTTP(s) URL, use [`jwk.Fetch()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Fetch)

If you are going to be using this key repeatedly in a long running process, consider using [`jwk.Cache`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Cache) or [`jwk.CachedSet`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#CachedSet) described elsewhere in this document.

By default, `jwk.Fetch()` uses an HTTP client that blocks HTTPS-to-HTTP redirect downgrades and limits redirect chains to 5 hops. This prevents the most common SSRF vector where an attacker-controlled JWKS URL redirects to an internal HTTP service.

When you supply your own client via `jwk.WithHTTPClient()` or `jwk.Configure(jwk.WithHTTPClient(...))`, the library uses it as-is — it does **not** automatically apply the default timeout or redirect policy. If you need to bring your own client (e.g. for custom TLS or proxy settings) while retaining the library's defaults, wrap it with [`jwk.WrapHTTPClientDefaults()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#WrapHTTPClientDefaults) before passing it:

```go
myClient := &http.Client{
  Transport: myCustomTransport,
}
jwk.Configure(jwk.WithHTTPClient(jwk.WrapHTTPClientDefaults(myClient)))
```

For full SSRF protection (blocking redirects to private IP ranges, DNS rebinding prevention), provide a custom `http.Client` with an appropriate `Transport.DialContext` that validates resolved IP addresses, and pass it via `jwk.WithHTTPClient()` or `jwk.Configure()`.

<!-- INCLUDE(examples/jwk_fetch_example_test.go) -->
```go
package examples_test

import (
  "context"
  "encoding/json"
  "fmt"
  "net/http"
  "net/http/httptest"
  "os"

  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_fetch() {
  srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, `{
  		"keys": [
        {"kty":"EC",
         "crv":"P-256",
         "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
         "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
         "use":"enc",
         "kid":"1"},
        {"kty":"RSA",
         "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
         "e":"AQAB",
         "alg":"RS256",
         "kid":"2011-04-29"}
      ]
    }`)
  }))
  defer srv.Close()

  set, err := jwk.Fetch(
    context.Background(),
    srv.URL,
    // This is necessary because httptest.Server is using a custom certificate
    jwk.WithHTTPClient(srv.Client()),
  )
  if err != nil {
    fmt.Printf("failed to fetch JWKS: %s\n", err)
    return
  }

  json.NewEncoder(os.Stdout).Encode(set)
  // OUTPUT:
  // {"keys":[{"crv":"P-256","kid":"1","kty":"EC","use":"enc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"},{"alg":"RS256","e":"AQAB","kid":"2011-04-29","kty":"RSA","n":"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"}]}
}
```
source: [examples/jwk_fetch_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_fetch_example_test.go)
<!-- END INCLUDE -->

## Auto-refreshing remote keys

Sometimes you need to fetch a remote JWK, and use it multiple times in a long-running process.
For example, you may act as an intermediary to some other service, and you may need to verify incoming JWT tokens against the tokens in said other service.

Normally, you should be able to simply fetch the JWK using [`jwk.Fetch()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Fetch),
but keys are usually routinely expired and rotated due to security reasons.
In such cases you would need to refetch the JWK periodically, which is a pain.

`github.com/lestrrat-go/jwx/v3/jwk` provides the [`jwk.Cache`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Cache) and [`jwk.CachedSet`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#CachedSet) to do this for you.

<!-- INCLUDE(examples/jwk_cache_example_test.go) -->
```go
package examples_test

import (
  "context"
  "fmt"
  "time"

  "github.com/lestrrat-go/httprc/v3"
  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_cache() {
  ctx, cancel := context.WithCancel(context.Background())
  defer cancel()

  const googleCerts = `https://www.googleapis.com/oauth2/v3/certs`

  // First, set up the `jwk.Cache` object. You need to pass it a
  // `context.Context` object to control the lifecycle of the background fetching goroutine.
  c, err := jwk.NewCache(ctx, httprc.NewClient())
  if err != nil {
    fmt.Printf("failed to create cache: %s\n", err)
    return
  }

  // Tell *jwk.Cache that we only want to refresh this JWKS periodically.
  if err := c.Register(ctx, googleCerts); err != nil {
    fmt.Printf("failed to register google JWKS: %s\n", err)
    return
  }

  // Pretend that this is your program's main loop
MAIN:
  for {
    select {
    case <-ctx.Done():
      break MAIN
    default:
    }
    keyset, err := c.Lookup(ctx, googleCerts)
    if err != nil {
      fmt.Printf("failed to fetch google JWKS: %s\n", err)
      return
    }
    _ = keyset
    // The returned `keyset` will always be "reasonably" new.
    //
    // By "reasonably" we mean that we cannot guarantee that the keys will be refreshed
    // immediately after it has been rotated in the remote source. But it should be close\
    // enough, and should you need to forcefully refresh the token using the `(jwk.Cache).Refresh()` method.
    //
    // If refetching the keyset fails, a cached version will be returned from the previous
    // successful sync

    // Do interesting stuff with the keyset... but here, we just
    // sleep for a bit
    time.Sleep(time.Second)

    // Because we're a dummy program, we just cancel the loop now.
    // If this were a real program, you presumably loop forever
    cancel()
  }
  // OUTPUT:
}
```
source: [examples/jwk_cache_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_cache_example_test.go)
<!-- END INCLUDE -->

<!-- INCLUDE(examples/jwk_cached_set_example_test.go) -->
```go
package examples_test

import (
  "context"
  "fmt"
  "log/slog"
  "os"
  "time"

  "github.com/lestrrat-go/httprc/v3"
  "github.com/lestrrat-go/httprc/v3/tracesink"
  "github.com/lestrrat-go/jwx/v3/jwk"
  "github.com/lestrrat-go/jwx/v3/jws"
)

func Example_jwk_cached_set() {
  ctx, cancel := context.WithCancel(context.Background())
  defer cancel()

  const googleCerts = `https://www.googleapis.com/oauth2/v3/certs`

  // The first steps are the same as examples/jwk_cache_example_test.go
  c, err := jwk.NewCache(
    ctx,
    httprc.NewClient(
      httprc.WithTraceSink(tracesink.NewSlog(slog.New(slog.NewJSONHandler(os.Stderr, nil)))),
    ),
  )
  if err != nil {
    fmt.Printf("failed to create cache: %s\n", err)
    return
  }

  // Register the URL to fetch the JWKS from. In this case, we're saying that
  // the cache can dynamically decide how often to refresh the keyset based on
  // the HTTP headers returned by the server, but the value must be at least
  // 1 hour, and at most 7 days.
  if err := c.Register(
    ctx,
    googleCerts,
    jwk.WithMaxInterval(24*time.Hour*7),
    jwk.WithMinInterval(15*time.Minute),
  ); err != nil {
    fmt.Printf("failed to register google JWKS: %s\n", err)
    return
  }

  cached, err := c.CachedSet(googleCerts)
  if err != nil {
    fmt.Printf("failed to get cached keyset: %s\n", err)
    return
  }

  // cached fulfills the jwk.Set interface.
  var _ jwk.Set = cached

  // That means you can pass it to things like jws.WithKeySet,
  // allowing you to pretend as if you are using the result of
  //
  //   jwk.Fetch(ctx, googleCerts)
  //
  // But you are instead using a cached (and periodically refreshed) set
  // for each operation.
  _ = jws.WithKeySet(cached)

  // OUTPUT:
}
```
source: [examples/jwk_cached_set_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_cached_set_example_test.go)
<!-- END INCLUDE -->

## Default Fetch Security Behavior

`jwk.Fetch()` does not apply a URL whitelist by default — it uses
`jwk.InsecureWhitelist{}`, which allows every URL. This keeps the
zero-config path short for the common case where the URL is a constant
in your own code or a value loaded from trusted configuration.

**If the URL comes from an untrusted source** — most commonly the `jku`
header of a JWS handed to you by a peer — you **must** pass a
`jwk.WithFetchWhitelist()` option that restricts which destinations the
library will contact. See [Using Whitelists](#using-whitelists) below for
the concrete whitelist types and an example.

Note that even with a whitelist, the default HTTP client will follow
redirects and does not inspect the resolved destination IP. For defense
against redirect-to-private-IP and DNS-rebinding attacks, combine the
whitelist with a custom `http.Client` (via `jwk.WithHTTPClient`) whose
`Transport.DialContext` validates addresses.

## Using Whitelists

If you are fetching JWK Sets from a possibly untrusted source such as the URL in the `jku` field of a JWS message,
you may have to perform some sort of whitelist checking. You can provide a `jwk.Whitelist` object to either
`jwk.Fetch()` or `(*jwk.Cache).Register()` methods to specify the use of a whitelist.

Currently the package provides `jwk.MapWhitelist` and `jwk.RegexpWhitelist` types for simpler cases,
as well as `jwk.InsecureWhitelist` for when you explicitly want to allow all URLs.
If you would like to implement something more complex, you can provide a function via `jwk.WhitelistFunc` or implement your own type of `jwk.Whitelist`.

**If you use `jwk.RegexpWhitelist`, anchor your patterns.** Patterns are **not** anchored for you, so a naive pattern matches anywhere in the URL and can allow far more than you intend. `www\.googleapis\.com` also matches hostile look-alikes such as `https://www.googleapis.com.attacker.com/evil` and `https://attacker.com/?x=www.googleapis.com` — a whitelist bypass that reopens the SSRF / key-substitution hole the whitelist was meant to close. Anchor the start with `^`, escape the literal dots (`\.`), and terminate the host with a `/` (e.g. `^https://www\.googleapis\.com/`, as in the example below). Prefer `jwk.MapWhitelist` when the set of URLs is known exactly.

<!-- INCLUDE(examples/jwk_whitelist_example_test.go) -->
```go
package examples_test

import (
  "context"
  "encoding/json"
  "fmt"
  "net/http"
  "net/http/httptest"
  "os"
  "regexp"

  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_whitelist() {
  srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, `{
  		"keys": [
        {"kty":"EC",
         "crv":"P-256",
         "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
         "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
         "use":"enc",
         "kid":"1"},
        {"kty":"RSA",
         "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
         "e":"AQAB",
         "alg":"RS256",
         "kid":"2011-04-29"}
      ]
    }`)
  }))
  defer srv.Close()

  testcases := []struct {
    Whitelist jwk.Whitelist
    Error     bool
  }{
    // The first two whitelists are meant to prevent access to any other
    // URLs other than www.google.com
    {
      Whitelist: jwk.NewMapWhitelist().Add(`https://www.googleapis.com/oauth2/v3/certs`),
      Error:     true,
    },
    // RegexpWhitelist patterns are NOT anchored for you. Always
    // anchor the start with ^, escape the literal dots (\.), and
    // terminate the host with a / so the pattern can only match the
    // origin you intend. The pattern below does exactly that. A
    // naive, unanchored `www\.googleapis\.com` would also match
    // hostile look-alikes such as
    // https://www.googleapis.com.attacker.com/evil or
    // https://attacker.com/?x=www.googleapis.com, silently turning
    // the allowlist into a bypass. Prefer MapWhitelist when the URL
    // set is known exactly; reach for RegexpWhitelist only when you
    // genuinely need patterns.
    {
      Whitelist: jwk.NewRegexpWhitelist().Add(regexp.MustCompile(`^https://www\.googleapis\.com/`)),
      Error:     true,
    },
    // This whitelist allows anything
    {
      Whitelist: jwk.InsecureWhitelist{},
    },
  }

  for _, tc := range testcases {
    set, err := jwk.Fetch(
      context.Background(),
      srv.URL,
      // This is necessary because httptest.Server is using a custom certificate
      jwk.WithHTTPClient(srv.Client()),
      // Pass the whitelist!
      jwk.WithFetchWhitelist(tc.Whitelist),
    )
    if tc.Error {
      if err == nil {
        fmt.Printf("expected fetch to fail, but got no error\n")
        return
      }
    } else {
      if err != nil {
        fmt.Printf("failed to fetch JWKS: %s\n", err)
        return
      }
      json.NewEncoder(os.Stdout).Encode(set)
    }
  }

  // OUTPUT:
  // {"keys":[{"crv":"P-256","kid":"1","kty":"EC","use":"enc","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"},{"alg":"RS256","e":"AQAB","kid":"2011-04-29","kty":"RSA","n":"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"}]}
}
```
source: [examples/jwk_whitelist_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_whitelist_example_test.go)
<!-- END INCLUDE -->

# Working with jwk.Key

## [Working with key-specific methods]

While you would almost always be able to get away with working with just the `jwk.Key` interface, there might be times when you want to get to methods that are specific to a particular key type, such as an RSA key.

In these cases it is possible to convert their types and get a more specific interface, such as `jwk.RSAPrivateKey`

<!-- INCLUDE(examples/jwk_key_specific_methods_example_test.go) -->
```go
package examples_test

import (
  "crypto/rand"
  "crypto/rsa"
  "fmt"

  "github.com/lestrrat-go/jwx/v3/jwk"
)

func Example_jwk_key_specific_metehods() {
  raw, err := rsa.GenerateKey(rand.Reader, 2048)
  if err != nil {
    fmt.Printf("failed to generate RSA private key: %s\n", err)
    return
  }

  key, err := jwk.Import(raw)
  if err != nil {
    fmt.Printf("failed to create jwk.Key from RSA private key: %s\n", err)
    return
  }

  rsakey, ok := key.(jwk.RSAPrivateKey)
  if !ok {
    fmt.Printf("failed to convert jwk.Key into jwk.RSAPrivateKey (was %T)\n", key)
    return
  }

  // We won't print these values, because each time they are
  // generated the contents will be different, and thus our
  // tests would fail. But here you can see that once you
  // convert the type you can access the RSA-specific methods
  _, _ = rsakey.D()
  _, _ = rsakey.DP()
  _, _ = rsakey.DQ()
  _, _ = rsakey.E()
  _, _ = rsakey.N()
  _, _ = rsakey.P()
  _, _ = rsakey.Q()
  _, _ = rsakey.QI()
  // OUTPUT:
  //
}
```
source: [examples/jwk_key_specific_methods_example_test.go](https://github.com/lestrrat-go/jwx/blob/v3/examples/jwk_key_specific_methods_example_test.go)
<!-- END INCLUDE -->

## Setting values to fields

Using [`jwk.Import()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Import) allows you to create a key whose fields have been properly populated, but sometimes there are other fields that you may want to populate in a key, such as`kid`, or other custom fields.

These fields can all be set using the [`jwk.Set()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Set) method.

The [`jwk.Set()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Set) method takes the name of the key and a value to be associated with it. Some predefined keys have specific types (in which type checks are enforced), and others don't.

[`jwk.Set()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Set) may not alter the Key Type (`kty`) field of a key.

The `jwk` package defines field key names for predefined keys as constants, so you won't ever have to bang your head against the wall after finding out that you have a typo.

```go
key.Set(jwk.KeyIDKey, `my-awesome-key`)
key.Set(`my-custom-field`, `unbelievable-value`)
```

## Converting a jwk.Key to a raw key

As discussed in [Terminology](#terminology), this package calls the "original" keys (e.g. `rsa.PublicKey`, `ecdsa.PrivateKey`, etc.) "raw" keys. To obtain a raw key from a  [`jwk.Key`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Key) object, use the [`Raw()`](https://github.com/github.com/lestrrat-go/jwx/v3/jwk#Raw) method.

```go
key, _ := jwk.ParseKey(src)

var raw interface{}
if err := key.Raw(&raw); err != nil {
  ...
}
```

In the above example, `raw` contains whatever the [`jwk.Key`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#Key) represents.
If `key` represents an RSA key, it will contain either a `rsa.PublicKey` or `rsa.PrivateKey`. If it represents an ECDSA key, an `ecdsa.PublicKey`, or `ecdsa.PrivateKey`, etc.

If the only operation that you are performing is to grab the raw key out of a JSON JWK, use [`jwk.ParseRawKey`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#ParseRawKey)

```go
var raw interface{}
if err := jwk.ParseRawKey(src, &raw); err != nil {
  ...
}
```

## Filtering Keys with KeyFilter

The [`jwk.KeyFilter`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#KeyFilter) interface provides a mechanism to selectively include or exclude specific fields when working with JWK keys. This is useful when you need to serialize keys with only certain fields, or when you want to create clean representations of keys for specific purposes.

KeyFilter objects provide two methods:
- `Filter()`: Returns a new key containing only the fields that should be included
- `Reject()`: Returns a new key with specified fields excluded

### Standard Field Filters

For convenience, the library provides pre-defined filters that include standard fields for each key type:

- [`jwk.RSAStandardFieldsFilter()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#RSAStandardFieldsFilter) - for RSA keys
- [`jwk.ECDSAStandardFieldsFilter()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#ECDSAStandardFieldsFilter) - for ECDSA keys  
- [`jwk.OKPStandardFieldsFilter()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#OKPStandardFieldsFilter) - for OKP keys
- [`jwk.SymmetricStandardFieldsFilter()`](https://pkg.go.dev/github.com/lestrrat-go/jwx/v3/jwk#SymmetricStandardFieldsFilter) - for symmetric keys

These functions return filters configured to include the standard fields defined in the JWK specification for each key type.
