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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jwt_test
import (
"bytes"
"encoding/json"
"fmt"
"log"
"time"
"github.com/tink-crypto/tink-go/v2/insecurecleartextkeyset"
"github.com/tink-crypto/tink-go/v2/jwt"
"github.com/tink-crypto/tink-go/v2/keyset"
)
// [START jwt-signature-example]
func Example_signAndVerify() {
// A private keyset created with
// "tinkey create-keyset --key-template=JWT_ES256 --out private_keyset.cfg".
// Note that this keyset has the secret key information in cleartext.
privateJSONKeyset := `{
"primaryKeyId": 1742360595,
"key": [
{
"keyData": {
"typeUrl": "type.googleapis.com/google.crypto.tink.JwtEcdsaPrivateKey",
"value": "GiBgVYdAPg3Fa2FVFymGDYrI1trHMzVjhVNEMpIxG7t0HRJGIiBeoDMF9LS5BDCh6YgqE3DjHwWwnEKEI3WpPf8izEx1rRogbjQTXrTcw/1HKiiZm2Hqv41w7Vd44M9koyY/+VsP+SAQAQ==",
"keyMaterialType": "ASYMMETRIC_PRIVATE"
},
"status": "ENABLED",
"keyId": 1742360595,
"outputPrefixType": "TINK"
}
]
}`
// The corresponding public keyset created with
// "tinkey create-public-keyset --in private_keyset.cfg"
publicJSONKeyset := `{
"primaryKeyId": 1742360595,
"key": [
{
"keyData": {
"typeUrl": "type.googleapis.com/google.crypto.tink.JwtEcdsaPublicKey",
"value": "EAEaIG40E1603MP9RyoomZth6r+NcO1XeODPZKMmP/lbD/kgIiBeoDMF9LS5BDCh6YgqE3DjHwWwnEKEI3WpPf8izEx1rQ==",
"keyMaterialType": "ASYMMETRIC_PUBLIC"
},
"status": "ENABLED",
"keyId": 1742360595,
"outputPrefixType": "TINK"
}
]
}`
// Create a keyset handle from the cleartext private keyset in the previous
// step. The keyset handle provides abstract access to the underlying keyset to
// limit the access of the raw key material.
//
// WARNING: In practice, it is unlikely you will want to use a insecurecleartextkeyset,
// as it implies that your key material is passed in cleartext, which is a security risk.
// consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault.
// See https://developers.google.com/tink/key-management-overview.
privateKeysetHandle, err := insecurecleartextkeyset.Read(
keyset.NewJSONReader(bytes.NewBufferString(privateJSONKeyset)))
if err != nil {
log.Fatal(err)
}
// Retrieve the JWT Signer primitive from privateKeysetHandle.
signer, err := jwt.NewSigner(privateKeysetHandle)
if err != nil {
log.Fatal(err)
}
// Use the primitive to create and sign a token. In this case, the primary key of the
// keyset will be used (which is also the only key in this example).
expiresAt := time.Now().Add(time.Hour)
audience := "example audience"
subject := "example subject"
rawJWT, err := jwt.NewRawJWT(&jwt.RawJWTOptions{
Audience: &audience,
Subject: &subject,
ExpiresAt: &expiresAt,
})
if err != nil {
log.Fatal(err)
}
token, err := signer.SignAndEncode(rawJWT)
if err != nil {
log.Fatal(err)
}
// Create a keyset handle from the keyset containing the public key. Because the
// public keyset does not contain any secrets, we can use [keyset.ReadWithNoSecrets].
publicKeysetHandle, err := keyset.ReadWithNoSecrets(
keyset.NewJSONReader(bytes.NewBufferString(publicJSONKeyset)))
if err != nil {
log.Fatal(err)
}
// Retrieve the Verifier primitive from publicKeysetHandle.
verifier, err := jwt.NewVerifier(publicKeysetHandle)
if err != nil {
log.Fatal(err)
}
// Verify the signed token.
validator, err := jwt.NewValidator(&jwt.ValidatorOpts{ExpectedAudience: &audience})
if err != nil {
log.Fatal(err)
}
verifiedJWT, err := verifier.VerifyAndDecode(token, validator)
if err != nil {
log.Fatal(err)
}
// Extract subject claim from the token.
if !verifiedJWT.HasSubject() {
log.Fatal(err)
}
extractedSubject, err := verifiedJWT.Subject()
if err != nil {
log.Fatal(err)
}
fmt.Println(extractedSubject)
// Output: example subject
}
// [END jwt-signature-example]
// [START jwt-generate-jwks-example]
func Example_generateJWKS() {
// A Tink keyset in JSON format with one JWT public key.
publicJSONKeyset := `{
"primaryKeyId": 1742360595,
"key": [
{
"keyData": {
"typeUrl": "type.googleapis.com/google.crypto.tink.JwtEcdsaPublicKey",
"value": "EAEaIG40E1603MP9RyoomZth6r+NcO1XeODPZKMmP/lbD/kgIiBeoDMF9LS5BDCh6YgqE3DjHwWwnEKEI3WpPf8izEx1rQ==",
"keyMaterialType": "ASYMMETRIC_PUBLIC"
},
"status": "ENABLED",
"keyId": 1742360595,
"outputPrefixType": "TINK"
}
]
}`
// Create a keyset handle from the keyset containing the public key. Because the
// public keyset does not contain any secrets, we can use [keyset.ReadWithNoSecrets].
publicKeysetHandle, err := keyset.ReadWithNoSecrets(
keyset.NewJSONReader(bytes.NewBufferString(publicJSONKeyset)))
if err != nil {
log.Fatal(err)
}
// Create a publicJWKset from publicKeysetHandle.
publicJWKset, err := jwt.JWKSetFromPublicKeysetHandle(publicKeysetHandle)
if err != nil {
log.Fatal(err)
}
// Remove whitespace so that we can compare it to the expected string.
compactPublicJWKset := &bytes.Buffer{}
err = json.Compact(compactPublicJWKset, publicJWKset)
if err != nil {
log.Fatal(err)
}
fmt.Println(compactPublicJWKset.String())
// Output:
// {"keys":[{"alg":"ES256","crv":"P-256","key_ops":["verify"],"kid":"Z9pQEw","kty":"EC","use":"sig","x":"bjQTXrTcw_1HKiiZm2Hqv41w7Vd44M9koyY_-VsP-SA","y":"XqAzBfS0uQQwoemIKhNw4x8FsJxChCN1qT3_IsxMda0"}]}
}
// [END jwt-generate-jwks-example]
// [START jwt-verify-with-jwks-example]
func Example_verifyWithJWKS() {
// A signed token with the subject 'example subject', audience 'example audience'.
// and expiration on 2023-03-23.
token := `eyJhbGciOiJFUzI1NiIsICJraWQiOiJaOXBRRXcifQ.eyJhdWQiOiJleGFtcGxlIGF1ZGllbmNlIiwgImV4cCI6MTY3OTUzMzIwMCwgInN1YiI6ImV4YW1wbGUgc3ViamVjdCJ9.ZvI0T84fJ1aouiB7n62kHOmbm0Hpfiz0JtYs15XVDT8KyoVYZ8hu_DGJUN47BqZIbuOI-rdu9TxJvutj8uF3Ow`
// A public keyset in the JWK set format.
publicJWKset := `{
"keys":[
{
"alg":"ES256",
"crv":"P-256",
"key_ops":["verify"],
"kid":"Z9pQEw",
"kty":"EC",
"use":"sig",
"x":"bjQTXrTcw_1HKiiZm2Hqv41w7Vd44M9koyY_-VsP-SA",
"y":"XqAzBfS0uQQwoemIKhNw4x8FsJxChCN1qT3_IsxMda0"
}
]
}`
// Create a keyset handle from publicJWKset.
publicKeysetHandle, err := jwt.JWKSetToPublicKeysetHandle([]byte(publicJWKset))
if err != nil {
log.Fatal(err)
}
// Retrieve the Verifier primitive from publicKeysetHandle.
verifier, err := jwt.NewVerifier(publicKeysetHandle)
if err != nil {
log.Fatal(err)
}
// Verify the signed token. For this example, we use a fixed date. Usually, you would
// either not set FixedNow, or set it to the current time.
audience := "example audience"
validator, err := jwt.NewValidator(&jwt.ValidatorOpts{
ExpectedAudience: &audience,
FixedNow: time.Date(2023, 3, 23, 0, 0, 0, 0, time.UTC),
})
if err != nil {
log.Fatal(err)
}
verifiedJWT, err := verifier.VerifyAndDecode(token, validator)
if err != nil {
log.Fatal(err)
}
// Extract subject claim from the token.
if !verifiedJWT.HasSubject() {
log.Fatal(err)
}
extractedSubject, err := verifiedJWT.Subject()
if err != nil {
log.Fatal(err)
}
fmt.Println(extractedSubject)
// Output: example subject
}
// [END jwt-verify-with-jwks-example]
// [START jwt-mac-example]
func Example_computeMACAndVerify() {
// Generate a keyset handle.
handle, err := keyset.NewHandle(jwt.HS256Template())
if err != nil {
log.Fatal(err)
}
// TODO: Save the keyset to a safe location. DO NOT hardcode it in source
// code. Consider encrypting it with a remote key in a KMS. .See
// https://developers.google.com/tink/key-management-overview.
// Create a token and compute a MAC for it.
expiresAt := time.Now().Add(time.Hour)
audience := "example audience"
customClaims := map[string]any{"custom": "my custom claim"}
rawJWT, err := jwt.NewRawJWT(&jwt.RawJWTOptions{
Audience: &audience,
CustomClaims: customClaims,
ExpiresAt: &expiresAt,
})
if err != nil {
log.Fatal(err)
}
mac, err := jwt.NewMAC(handle)
if err != nil {
log.Fatal(err)
}
token, err := mac.ComputeMACAndEncode(rawJWT)
if err != nil {
log.Fatal(err)
}
// Verify the MAC.
validator, err := jwt.NewValidator(&jwt.ValidatorOpts{ExpectedAudience: &audience})
if err != nil {
log.Fatal(err)
}
verifiedJWT, err := mac.VerifyMACAndDecode(token, validator)
if err != nil {
log.Fatal(err)
}
// Extract a custom claim from the token.
if !verifiedJWT.HasStringClaim("custom") {
log.Fatal(err)
}
extractedCustomClaim, err := verifiedJWT.StringClaim("custom")
if err != nil {
log.Fatal(err)
}
fmt.Println(extractedCustomClaim)
// Output: my custom claim
}
// [END jwt-mac-example]
|