jwt

package
v0.0.0-...-d6de17e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 13, 2023 License: Apache-2.0 Imports: 30 Imported by: 2

Documentation

Overview

Package jwt implements a subset of JSON Web Token (JWT) as defined by RFC 7519 (https://tools.ietf.org/html/rfc7519) that is considered safe and most often used.

Example (ComputeMACAndVerify)
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/tink-crypto/tink-go/jwt"
	"github.com/tink-crypto/tink-go/keyset"
)

func main() {
	// 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://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets

	// Create a token and compute a MAC for it.
	expiresAt := time.Now().Add(time.Hour)
	audience := "example audience"
	customClaims := map[string]interface{}{"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
Example (SignAndVerify)
package main

import (
	"bytes"
	"fmt"
	"log"
	"time"

	"github.com/tink-crypto/tink-go/insecurecleartextkeyset"
	"github.com/tink-crypto/tink-go/jwt"
	"github.com/tink-crypto/tink-go/keyset"
)

func main() {
	// A private keyset created with
	// "tinkey create-keyset --key-template=JWT_RS256_2048_F4 --out private_keyset.cfg".
	// Note that this keyset has the secret key information in cleartext.
	privateJSONKeyset := `{
		"primaryKeyId": 185188009,
		"key": [
			{
				"keyData": {
					"typeUrl": "type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey",
					"value": "EosCEAEagQIAs9iifvWObNLbP+x7zupVIYTdHKba4VFgJEnnGtIII21R+KGddTdvNGAokd4GPrFk1GDPitHrAAoW1+NWrafsEUi2J9Sy3uwEyarsKDggewoBCNg2fcWAiZXplPjUyTlhrLvTuyrcL/mGPy+ib7bdmov+D2EP+rKUH6/ydtQGiyHRR3uurTUWfrMD1/6WaBVfngpy5Pxs2nuHXRmBHQKWmPfvErgr4abdjhKDaWIuxzSise1CSAbiWTNcxpIuFYZgPjgQzpqeh93LUXIX9YJds/bhHtXqRdxk6yTisloHOZETItK/rHCCE25dLkkaJ2Li7AtnJdBc6tEUNiuFj2JCjSIDAQABGoACT2lWxwySaQbp/N3lBUZ/dJ+AKsiaWWdfNmbTfwpCwbHhwhFKv5lMpynWgCIzS7d0uDpPKhLq20eZMpaVjXRaTn92vzuyB7DbpFiukkvGO839CvS9iueMjDP/weHlwzxtHqKJKVoRg7WAS6Iy7XUngLhT5GKNdbsooJ1GSKXyhbgWyMcspKSQe4lZXUntVMK5z4iLNmcQwsBp8yM55mZra13TXowob/E/wd+tGiABCn6CDt8G1gXzWDaoF2tt6WhSGZbXUVGagmoea/BWeAuJyKSSi5h+uPpc5SPhGvyKfSEVaCs2QeM7/UIXhzAcx2j/VqySb6y9EbSiJfy8vr49QSKBAQD+AbFCGHd9kZ5LIQrfe9caOxS9pQPdFkBJESw0C3x2uBIg8awiQsuVXMeEgyGLyWBZoi2x98OMSR9OzCuSLtb7Nv0Wqn0LUj4WPRdmg//uLeD3O2rcVRIR4db/B8WvXnK2uQsqwGDyh4BepGvprXQPYMX2uwnBGL2ccS2De53HJSqBAQC1QfOi4egjmlmXqJLpISUSN1NixkIi8EJHaZZ0YrbaRrEyiJczthcazNHFt6gzgOcosFaKaZeqps4Tet+5NgS7eh7RzLQ2+cfT4ewpT2ExJ4NsOy8XDqD6GRjliLxjGAoUf24s3B+3LLACPiQjeeZGJP0ivh384WabyXXxRgHFSTKBAQChl7gKIYCbHPHEQAAnzyQ4Js/6GinMFCTPlyI09f23lUDLPpRQs4fKvNydO8Myp+ko/NjvOH1qGPbW7WLmu+++n+wA6HNmqWqgQTtK170Q7JULE/zWsTQutitN0cb82yxFfJFTIFJM2NFc5GNWpSeJxPoMDk+VTcUK6qGW3SSyFTqBAQCeaPFA3SZAV1kNjio2zNzVOr0JijOqzUdfmgv/03Xy9e1POMjMTMuMhIygu42o1XMwwEwh037Vicp4g96aw3cHUgc1XC30DgByUPRQdit/BgV5xY+2GvbdHKoBkKrz/8Jvf58OXaLqN4frrdtvlc2GaDVC89zJcUR3ym3lW0WY4UKBAQD6MCruwXaxXJMxjtlH1YT5ow4R5neeiswNfGj4Ta/WbWyiVA60zpdNbGqH+etmiHY8+aBb/H4O9+JhOcBtlMLN4UlK1jg8wPSemZjsIPiUZXHkeIUa2RTUSz90wgz7aOqC0lYsLLFaJNWs54fC9LpZ0JzoqYDI8iDPnlE7xaag9g==",
					"keyMaterialType": "ASYMMETRIC_PRIVATE"
				},
				"status": "ENABLED",
				"keyId": 185188009,
				"outputPrefixType": "TINK"
			}
		]
	}`

	// The corresponding public keyset created with
	// "tinkey create-public-keyset --in private_keyset.cfg"
	publicJSONKeyset := `{
		"primaryKeyId": 185188009,
		"key": [
			{
				"keyData": {
					"typeUrl": "type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PublicKey",
					"value": "EAEagQIAs9iifvWObNLbP+x7zupVIYTdHKba4VFgJEnnGtIII21R+KGddTdvNGAokd4GPrFk1GDPitHrAAoW1+NWrafsEUi2J9Sy3uwEyarsKDggewoBCNg2fcWAiZXplPjUyTlhrLvTuyrcL/mGPy+ib7bdmov+D2EP+rKUH6/ydtQGiyHRR3uurTUWfrMD1/6WaBVfngpy5Pxs2nuHXRmBHQKWmPfvErgr4abdjhKDaWIuxzSise1CSAbiWTNcxpIuFYZgPjgQzpqeh93LUXIX9YJds/bhHtXqRdxk6yTisloHOZETItK/rHCCE25dLkkaJ2Li7AtnJdBc6tEUNiuFj2JCjSIDAQAB",
					"keyMaterialType": "ASYMMETRIC_PUBLIC"
				},
				"status": "ENABLED",
				"keyId": 185188009,
				"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://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets.
	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
Example (VerifyWithJWKS)
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/tink-crypto/tink-go/jwt"
)

func main() {
	// A signed token with the subject 'example subject', audience 'example audience'.
	// and expiration on 2023-03-23.
	token := `eyJhbGciOiJSUzI1NiIsImtpZCI6IkN3bS1xUSJ9.eyJhdWQiOiJleGFtcGxlIGF1ZGllbmNlIiwiZXhwIjoxNjc5NTcyODQzLCJzdWIiOiJleGFtcGxlIHN1YmplY3QifQ.dUPhvdmEnGuyESLBQn5OC3QmnRcJlcMfxDPsZ2wfqBK9poQag94xLxBnkzSZnhPP2gQcIt2aOCFeftL1MK3boI3g887J2hZ6hJmeABVi82YGK16P6LIgZuALdjiUcyexus5sxcEo2iuELzUy0hOzS2dDQWOoWCznltGFuavNQGW8A2365JScCsQeoDLAa-IX89vJww0uQVRZ8AxYigLJ5DhILtu-Lssq5sSpT28XASAMzafuYvAI60Cw8nvxTaheRA8AkTI9DWERV4Z-0UQNV2O61U6_24hkjIYCGpuz8_5vBB-W3jijIdWf8J1BNyBfjNeh9eXgSZh8J3wBCEb98Q`

	// A public keyset in the JWK set format.
	publicJWKset := `{
		"keys":[
			{
				"alg":"RS256",
				"e":"AQAB",
				"key_ops":["verify"],
				"kid":"Cwm-qQ",
				"kty":"RSA",
				"n":"ALPYon71jmzS2z_se87qVSGE3Rym2uFRYCRJ5xrSCCNtUfihnXU3bzRgKJHeBj6xZNRgz4rR6wAKFtfjVq2n7BFItifUst7sBMmq7Cg4IHsKAQjYNn3FgImV6ZT41Mk5Yay707sq3C_5hj8vom-23ZqL_g9hD_qylB-v8nbUBosh0Ud7rq01Fn6zA9f-lmgVX54KcuT8bNp7h10ZgR0Clpj37xK4K-Gm3Y4Sg2liLsc0orHtQkgG4lkzXMaSLhWGYD44EM6anofdy1FyF_WCXbP24R7V6kXcZOsk4rJaBzmREyLSv6xwghNuXS5JGidi4uwLZyXQXOrRFDYrhY9iQo0",
				"use":"sig"
			}
		]
	}`

	// 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

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ES256Template

func ES256Template() *tinkpb.KeyTemplate

ES256Template creates a JWT key template for JWA algorithm "ES256", which is digital signature with the NIST P-256 curve. It will set a key ID header "kid" in the token.

func ES384Template

func ES384Template() *tinkpb.KeyTemplate

ES384Template creates a JWT key template for JWA algorithm "ES384", which is digital signature with the NIST P-384 curve. It will set a key ID header "kid" in the token.

func ES512Template

func ES512Template() *tinkpb.KeyTemplate

ES512Template creates a JWT key template for JWA algorithm "ES512", which is digital signature with the NIST P-521 curve. It will set a key ID header "kid" in the token.

func HS256Template

func HS256Template() *tinkpb.KeyTemplate

HS256Template creates a JWT key template for JWA algorithm "HS256", which is a HMAC-SHA256 with a 32 byte key. It will set a key ID header "kid" in the token.

func HS384Template

func HS384Template() *tinkpb.KeyTemplate

HS384Template creates a JWT key template for JWA algorithm "HS384", which is a HMAC-SHA384 with a 48 byte key. It will set a key ID header "kid" in the token.

func HS512Template

func HS512Template() *tinkpb.KeyTemplate

HS512Template creates a JWT key template for JWA algorithm "HS512", which is a HMAC-SHA512 with a 64 byte key. It will set a key ID header "kid" in the token.

func IsExpirationErr

func IsExpirationErr(err error) bool

IsExpirationErr returns true if err was returned by a JWT verification for a token with a valid signature that is expired.

Note that if the corresponding verification key has been removed from the keyset, verification will not return an expiration error even if the token is expired, because the expiration is only verified if the signature is valid.

func JWKSetFromPublicKeysetHandle

func JWKSetFromPublicKeysetHandle(kh *keyset.Handle) ([]byte, error)

JWKSetFromPublicKeysetHandle converts a Tink KeysetHandle with JWT keys into a Json Web Key (JWK) set. Currently only public keys for algorithms ES256, ES384, ES512, RS256, RS384, and RS512 are supported. JWK is defined in https://www.rfc-editor.org/rfc/rfc7517.html.

func JWKSetToPublicKeysetHandle

func JWKSetToPublicKeysetHandle(jwkSet []byte) (*keyset.Handle, error)

JWKSetToPublicKeysetHandle converts a Json Web Key (JWK) set into a Tink KeysetHandle. It requires that all keys in the set have the "alg" field set. Currently, only public keys for algorithms ES256, ES384, ES512, RS256, RS384, and RS512 are supported. JWK is defined in https://www.rfc-editor.org/rfc/rfc7517.txt.

func PS256_2048_F4_Key_Template

func PS256_2048_F4_Key_Template() *tinkpb.KeyTemplate

PS256_2048_F4_Key_Template creates a JWT key template for JWA algorithm "PS256", which is digital signature with RSA-SSA-PSS, a 2048 bit modulus, and SHA256. It will set a key ID header "kid" in the token.

func PS256_3072_F4_Key_Template

func PS256_3072_F4_Key_Template() *tinkpb.KeyTemplate

PS256_3072_F4_Key_Template creates a JWT key template for JWA algorithm "PS256", which is digital signature with RSA-SSA-PSS, a 3072 bit modulus, and SHA256. It will set a key ID header "kid" in the token.

func PS384_3072_F4_Key_Template

func PS384_3072_F4_Key_Template() *tinkpb.KeyTemplate

PS384_3072_F4_Key_Template creates a JWT key template for JWA algorithm "PS384", which is digital signature with RSA-SSA-PSS, a 3072 bit modulus, and SHA384. It will set a key ID header "kid" in the token.

func PS512_4096_F4_Key_Template

func PS512_4096_F4_Key_Template() *tinkpb.KeyTemplate

PS512_4096_F4_Key_Template creates a JWT key template for JWA algorithm "PS512", which is digital signature with RSA-SSA-PSS, a 4096 bit modulus, and SHA512. It will set a key ID header "kid" in the token.

func RS256_2048_F4_Key_Template

func RS256_2048_F4_Key_Template() *tinkpb.KeyTemplate

RS256_2048_F4_Key_Template creates a JWT key template for JWA algorithm "RS256", which is digital signature with RSA-SSA-PKCS1 and SHA256. It will set a key ID header "kid" in the token.

func RS256_3072_F4_Key_Template

func RS256_3072_F4_Key_Template() *tinkpb.KeyTemplate

RS256_3072_F4_Key_Template creates a JWT key template for JWA algorithm "RS256", which is digital signature with RSA-SSA-PKCS1 and SHA256. It will set a key ID header "kid" in the token.

func RS384_3072_F4_Key_Template

func RS384_3072_F4_Key_Template() *tinkpb.KeyTemplate

RS384_3072_F4_Key_Template creates a JWT key template for JWA algorithm "RS384", which is digital signature with RSA-SSA-PKCS1 and SHA384. It will set a key ID header "kid" in the token.

func RS512_4096_F4_Key_Template

func RS512_4096_F4_Key_Template() *tinkpb.KeyTemplate

RS512_4096_F4_Key_Template creates a JWT key template for JWA algorithm "RS512", which is digital signature with RSA-SSA-PKCS1 and SHA512. It will set a key ID header "kid" in the token.

func RawES256Template

func RawES256Template() *tinkpb.KeyTemplate

RawES256Template creates a JWT key template for JWA algorithm "ES256", which is digital signature with the NIST P-256 curve. It will not set a key ID header "kid" in the token.

func RawES384Template

func RawES384Template() *tinkpb.KeyTemplate

RawES384Template creates a JWT key template for JWA algorithm "ES384", which is digital signature with the NIST P-384 curve. It will not set a key ID header "kid" in the token.

func RawES512Template

func RawES512Template() *tinkpb.KeyTemplate

RawES512Template creates a JWT key template for JWA algorithm "ES512", which is digital signature with the NIST P-521 curve. It will not set a key ID header "kid" in the token.

func RawHS256Template

func RawHS256Template() *tinkpb.KeyTemplate

RawHS256Template creates a JWT key template for JWA algorithm "HS256", which is a HMAC-SHA256 with a 32 byte key. It will not set a key ID header "kid" in the token.

func RawHS384Template

func RawHS384Template() *tinkpb.KeyTemplate

RawHS384Template creates a JWT key template for JWA algorithm "HS384", which is a HMAC-SHA384 with a 48 byte key. It will not set a key ID header "kid" in the token.

func RawHS512Template

func RawHS512Template() *tinkpb.KeyTemplate

RawHS512Template creates a JWT key template for JWA algorithm "HS512", which is a HMAC-SHA512 with a 64 byte key. It will not set a key ID header "kid" in the token.

func RawPS256_2048_F4_Key_Template

func RawPS256_2048_F4_Key_Template() *tinkpb.KeyTemplate

RawPS256_2048_F4_Key_Template creates a JWT key template for JWA algorithm "PS256", which is digital signature with RSA-SSA-PSS, a 2048 bit modulus, and SHA256. It will not set a key ID header "kid" in the token.

func RawPS256_3072_F4_Key_Template

func RawPS256_3072_F4_Key_Template() *tinkpb.KeyTemplate

RawPS256_3072_F4_Key_Template creates a JWT key template for JWA algorithm "PS256", which is digital signature with RSA-SSA-PSS, a 3072 bit modulus, and SHA256. It will not set a key ID header "kid" in the token.

func RawPS384_3072_F4_Key_Template

func RawPS384_3072_F4_Key_Template() *tinkpb.KeyTemplate

RawPS384_3072_F4_Key_Template creates a JWT key template for JWA algorithm "PS384", which is digital signature with RSA-SSA-PSS, a 3072 bit modulus, and SHA384. It will not set a key ID header "kid" in the token.

func RawPS512_4096_F4_Key_Template

func RawPS512_4096_F4_Key_Template() *tinkpb.KeyTemplate

RawPS512_4096_F4_Key_Template creates a JWT key template for JWA algorithm "PS512", which is digital signature with RSA-SSA-PSS, a 4096 bit modulus, and SHA512. It will not set a key ID header "kid" in the token.

func RawRS256_2048_F4_Key_Template

func RawRS256_2048_F4_Key_Template() *tinkpb.KeyTemplate

RawRS256_2048_F4_Key_Template creates a JWT key template for JWA algorithm "RS256", which is digital signature with RSA-SSA-PKCS1 and SHA256. It will not set a key ID header "kid" in the token.

func RawRS256_3072_F4_Key_Template

func RawRS256_3072_F4_Key_Template() *tinkpb.KeyTemplate

RawRS256_3072_F4_Key_Template creates a JWT key template for JWA algorithm "RS256", which is digital signature with RSA-SSA-PKCS1 and SHA256. It will not set a key ID header "kid" in the token.

func RawRS384_3072_F4_Key_Template

func RawRS384_3072_F4_Key_Template() *tinkpb.KeyTemplate

RawRS384_3072_F4_Key_Template creates a JWT key template for JWA algorithm "RS384", which is digital signature with RSA-SSA-PKCS1 and SHA384. It will not set a key ID header "kid" in the token.

func RawRS512_4096_F4_Key_Template

func RawRS512_4096_F4_Key_Template() *tinkpb.KeyTemplate

RawRS512_4096_F4_Key_Template creates a JWT key template for JWA algorithm "RS512", which is digital signature with RSA-SSA-PKCS1 and SHA512. It will not set a key ID header "kid" in the token.

Types

type MAC

type MAC interface {
	// Computes a MAC and encodes the raw JWT token and the MAC in the JWS compact serialization format.
	ComputeMACAndEncode(token *RawJWT) (string, error)

	// Verifies and decodes a JWT token in the JWS compact serialization format.
	//
	// The JWT is validated against the rules in validator. That is, every claim
	// in validator must also be present in the JWT. For example, if validator
	// contains an issuer (iss) claim, the JWT must contain an identical claim.
	// The JWT can contain claims that are NOT in the validator. However, if the
	// JWT contains a list of audiences, the validator must also contain an
	// audience in the list.
	//
	// If the JWT contains timestamp claims such as expiration (exp), issued_at
	// (iat) or not_before (nbf), they will also be validated. validator allows to
	// set a clock skew, to deal with small clock differences among different
	// machines.
	VerifyMACAndDecode(compact string, validator *Validator) (*VerifiedJWT, error)
}

MAC is an interface for authenticating and verifying JSON Web Tokens (JWT) with JSON Web Signature (JWS) MAC. See RFC 7519 and RFC 7515. Security guarantees: similar to Message Authentication Code (MAC).

func NewMAC

func NewMAC(handle *keyset.Handle) (MAC, error)

NewMAC generates a new instance of the JWT MAC primitive.

type RawJWT

type RawJWT struct {
	// contains filtered or unexported fields
}

RawJWT is an unsigned JSON Web Token (JWT), https://tools.ietf.org/html/rfc7519.

func NewRawJWT

func NewRawJWT(opts *RawJWTOptions) (*RawJWT, error)

NewRawJWT constructs a new RawJWT token based on the RawJwtOptions provided.

func NewRawJWTFromJSON

func NewRawJWTFromJSON(typeHeader *string, jsonPayload []byte) (*RawJWT, error)

NewRawJWTFromJSON builds a RawJWT from a marshaled JSON. Users shouldn't call this function and instead use NewRawJWT.

func (*RawJWT) ArrayClaim

func (r *RawJWT) ArrayClaim(name string) ([]interface{}, error)

ArrayClaim returns a slice representing a JSON array for a claim or an error if the claim is empty.

func (*RawJWT) Audiences

func (r *RawJWT) Audiences() ([]string, error)

Audiences returns a list of audiences from the 'aud' claim. If the 'aud' claim is a single string, it is converted into a list with a single entry.

func (*RawJWT) BooleanClaim

func (r *RawJWT) BooleanClaim(name string) (bool, error)

BooleanClaim returns a custom bool claim or an error if no claim is present.

func (*RawJWT) CustomClaimNames

func (r *RawJWT) CustomClaimNames() []string

CustomClaimNames returns a list with the name of custom claims in a RawJWT.

func (*RawJWT) ExpiresAt

func (r *RawJWT) ExpiresAt() (time.Time, error)

ExpiresAt returns the expiration claim ('exp') or an error if no claim is present.

func (*RawJWT) HasArrayClaim

func (r *RawJWT) HasArrayClaim(name string) bool

HasArrayClaim checks whether a claim of type list is present.

func (*RawJWT) HasAudiences

func (r *RawJWT) HasAudiences() bool

HasAudiences checks whether a JWT contains the audience claim ('aud').

func (*RawJWT) HasBooleanClaim

func (r *RawJWT) HasBooleanClaim(name string) bool

HasBooleanClaim checks whether a claim of type boolean is present.

func (*RawJWT) HasExpiration

func (r *RawJWT) HasExpiration() bool

HasExpiration checks whether a JWT contains an expiration time claim ('exp').

func (*RawJWT) HasIssuedAt

func (r *RawJWT) HasIssuedAt() bool

HasIssuedAt checks whether a JWT contains an issued at claim ('iat').

func (*RawJWT) HasIssuer

func (r *RawJWT) HasIssuer() bool

HasIssuer checks whether a JWT contains an issuer claim ('iss').

func (*RawJWT) HasJWTID

func (r *RawJWT) HasJWTID() bool

HasJWTID checks whether a JWT contains an JWT ID claim ('jti').

func (*RawJWT) HasNotBefore

func (r *RawJWT) HasNotBefore() bool

HasNotBefore checks whether a JWT contains a not before claim ('nbf').

func (*RawJWT) HasNullClaim

func (r *RawJWT) HasNullClaim(name string) bool

HasNullClaim checks whether a claim of type null is present.

func (*RawJWT) HasNumberClaim

func (r *RawJWT) HasNumberClaim(name string) bool

HasNumberClaim checks whether a claim of type number is present.

func (*RawJWT) HasObjectClaim

func (r *RawJWT) HasObjectClaim(name string) bool

HasObjectClaim checks whether a claim of type JSON object is present.

func (*RawJWT) HasStringClaim

func (r *RawJWT) HasStringClaim(name string) bool

HasStringClaim checks whether a claim of type string is present.

func (*RawJWT) HasSubject

func (r *RawJWT) HasSubject() bool

HasSubject checks whether a JWT contains an issuer claim ('sub').

func (*RawJWT) HasTypeHeader

func (r *RawJWT) HasTypeHeader() bool

HasTypeHeader returns whether a RawJWT contains a type header.

func (*RawJWT) IssuedAt

func (r *RawJWT) IssuedAt() (time.Time, error)

IssuedAt returns the issued at claim ('iat') or an error if no claim is present.

func (*RawJWT) Issuer

func (r *RawJWT) Issuer() (string, error)

Issuer returns the issuer claim ('iss') or an error if no claim is present.

func (*RawJWT) JSONPayload

func (r *RawJWT) JSONPayload() ([]byte, error)

JSONPayload marshals a RawJWT payload to JSON.

func (*RawJWT) JWTID

func (r *RawJWT) JWTID() (string, error)

JWTID returns the JWT ID claim ('jti') or an error if no claim is present.

func (*RawJWT) NotBefore

func (r *RawJWT) NotBefore() (time.Time, error)

NotBefore returns the not before claim ('nbf') or an error if no claim is present.

func (*RawJWT) NumberClaim

func (r *RawJWT) NumberClaim(name string) (float64, error)

NumberClaim returns a custom number claim or an error if no claim is present.

func (*RawJWT) ObjectClaim

func (r *RawJWT) ObjectClaim(name string) (map[string]interface{}, error)

ObjectClaim returns a map representing a JSON object for a claim or an error if the claim is empty.

func (*RawJWT) StringClaim

func (r *RawJWT) StringClaim(name string) (string, error)

StringClaim returns a custom string claim or an error if no claim is present.

func (*RawJWT) Subject

func (r *RawJWT) Subject() (string, error)

Subject returns the subject claim ('sub') or an error if no claim is present.

func (*RawJWT) TypeHeader

func (r *RawJWT) TypeHeader() (string, error)

TypeHeader returns the JWT type header.

type RawJWTOptions

type RawJWTOptions struct {
	Audiences    []string
	Audience     *string
	Subject      *string
	Issuer       *string
	JWTID        *string
	IssuedAt     *time.Time
	ExpiresAt    *time.Time
	NotBefore    *time.Time
	CustomClaims map[string]interface{}

	TypeHeader        *string
	WithoutExpiration bool
}

RawJWTOptions represent an unsigned JSON Web Token (JWT), https://tools.ietf.org/html/rfc7519.

It contains all payload claims and a subset of the headers. It does not contain any headers that depend on the key, such as "alg" or "kid", because these headers are chosen when the token is signed and encoded, and should not be chosen by the user. This ensures that the key can be changed without any changes to the user code.

type Signer

type Signer interface {
	// Computes a signature, and encodes the JWT and the signature in the JWS compact serialization format.
	SignAndEncode(rawJWT *RawJWT) (string, error)
}

Signer is the interface for signing JWTs. See RFC 7519 and RFC 7515. Security guarantees: similar to tink.Signer.

func NewSigner

func NewSigner(handle *keyset.Handle) (Signer, error)

NewSigner generates a new instance of the JWT Signer primitive.

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator defines how JSON Web Tokens (JWT) should be validated.

func NewValidator

func NewValidator(opts *ValidatorOpts) (*Validator, error)

NewValidator creates a new Validator.

func (*Validator) Validate

func (v *Validator) Validate(rawJWT *RawJWT) error

Validate validates a rawJWT according to the options provided.

type ValidatorOpts

type ValidatorOpts struct {
	ExpectedTypeHeader *string
	ExpectedIssuer     *string
	ExpectedAudience   *string

	IgnoreTypeHeader bool
	IgnoreAudiences  bool
	IgnoreIssuer     bool

	AllowMissingExpiration bool
	ExpectIssuedInThePast  bool

	ClockSkew time.Duration
	FixedNow  time.Time

	// Deprecated: Use ExpectedAudience instead.
	ExpectedAudiences *string
}

ValidatorOpts define validation options for JWT validators.

type VerifiedJWT

type VerifiedJWT struct {
	// contains filtered or unexported fields
}

VerifiedJWT is a verified JWT token.

func (*VerifiedJWT) ArrayClaim

func (v *VerifiedJWT) ArrayClaim(name string) ([]interface{}, error)

ArrayClaim returns a slice representing a JSON array for a claim or an error if the claim is empty.

func (*VerifiedJWT) Audiences

func (v *VerifiedJWT) Audiences() ([]string, error)

Audiences returns a list of audiences from the 'aud' claim. If the 'aud' claim is a single string, it is converted into a list with a single entry.

func (*VerifiedJWT) BooleanClaim

func (v *VerifiedJWT) BooleanClaim(name string) (bool, error)

BooleanClaim returns a custom bool claim or an error if no claim is present.

func (*VerifiedJWT) CustomClaimNames

func (v *VerifiedJWT) CustomClaimNames() []string

CustomClaimNames returns a list with the name of custom claims in a VerifiedJWT.

func (*VerifiedJWT) ExpiresAt

func (v *VerifiedJWT) ExpiresAt() (time.Time, error)

ExpiresAt returns the expiration claim ('exp') or an error if no claim is present.

func (*VerifiedJWT) HasArrayClaim

func (v *VerifiedJWT) HasArrayClaim(name string) bool

HasArrayClaim checks whether a claim of type list is present.

func (*VerifiedJWT) HasAudiences

func (v *VerifiedJWT) HasAudiences() bool

HasAudiences checks whether a JWT contains the audience claim ('aud').

func (*VerifiedJWT) HasBooleanClaim

func (v *VerifiedJWT) HasBooleanClaim(name string) bool

HasBooleanClaim checks whether a claim of type boolean is present.

func (*VerifiedJWT) HasExpiration

func (v *VerifiedJWT) HasExpiration() bool

HasExpiration checks whether a JWT contains an expiration time claim ('exp').

func (*VerifiedJWT) HasIssuedAt

func (v *VerifiedJWT) HasIssuedAt() bool

HasIssuedAt checks whether a JWT contains an issued at claim ('iat').

func (*VerifiedJWT) HasIssuer

func (v *VerifiedJWT) HasIssuer() bool

HasIssuer checks whether a JWT contains an issuer claim ('iss').

func (*VerifiedJWT) HasJWTID

func (v *VerifiedJWT) HasJWTID() bool

HasJWTID checks whether a JWT contains an JWT ID claim ('jti').

func (*VerifiedJWT) HasNotBefore

func (v *VerifiedJWT) HasNotBefore() bool

HasNotBefore checks whether a JWT contains a not before claim ('nbf').

func (*VerifiedJWT) HasNullClaim

func (v *VerifiedJWT) HasNullClaim(name string) bool

HasNullClaim checks whether a claim of type null is present.

func (*VerifiedJWT) HasNumberClaim

func (v *VerifiedJWT) HasNumberClaim(name string) bool

HasNumberClaim checks whether a claim of type number is present.

func (*VerifiedJWT) HasObjectClaim

func (v *VerifiedJWT) HasObjectClaim(name string) bool

HasObjectClaim checks whether a claim of type JSON object is present.

func (*VerifiedJWT) HasStringClaim

func (v *VerifiedJWT) HasStringClaim(name string) bool

HasStringClaim checks whether a claim of type string is present.

func (*VerifiedJWT) HasSubject

func (v *VerifiedJWT) HasSubject() bool

HasSubject checks whether a JWT contains an issuer claim ('sub').

func (*VerifiedJWT) HasTypeHeader

func (v *VerifiedJWT) HasTypeHeader() bool

HasTypeHeader return whether a RawJWT contains a type header.

func (*VerifiedJWT) IssuedAt

func (v *VerifiedJWT) IssuedAt() (time.Time, error)

IssuedAt returns the issued at claim ('iat') or an error if no claim is present.

func (*VerifiedJWT) Issuer

func (v *VerifiedJWT) Issuer() (string, error)

Issuer returns the issuer claim ('iss') or an error if no claim is present.

func (*VerifiedJWT) JSONPayload

func (v *VerifiedJWT) JSONPayload() ([]byte, error)

JSONPayload marshals a VerifiedJWT payload to JSON.

func (*VerifiedJWT) JWTID

func (v *VerifiedJWT) JWTID() (string, error)

JWTID returns the JWT ID claim ('jti') or an error if no claim is present.

func (*VerifiedJWT) NotBefore

func (v *VerifiedJWT) NotBefore() (time.Time, error)

NotBefore returns the not before claim ('nbf') or an error if no claim is present.

func (*VerifiedJWT) NumberClaim

func (v *VerifiedJWT) NumberClaim(name string) (float64, error)

NumberClaim returns a custom number claim or an error if no claim is present.

func (*VerifiedJWT) ObjectClaim

func (v *VerifiedJWT) ObjectClaim(name string) (map[string]interface{}, error)

ObjectClaim returns a map representing a JSON object for a claim or an error if the claim is empty.

func (*VerifiedJWT) StringClaim

func (v *VerifiedJWT) StringClaim(name string) (string, error)

StringClaim returns a custom string claim or an error if no claim is present.

func (*VerifiedJWT) Subject

func (v *VerifiedJWT) Subject() (string, error)

Subject returns the subject claim ('sub') or an error if no claim is present.

func (*VerifiedJWT) TypeHeader

func (v *VerifiedJWT) TypeHeader() (string, error)

TypeHeader returns the JWT type header.

type Verifier

type Verifier interface {
	// Verifies and decodes a JWT token in the JWS compact serialization format.
	//
	// The JWT is validated against the rules in validator. That is, every claim
	// in validator must also be present in the JWT. For example, if validator
	// contains an issuer (iss) claim, the JWT must contain an identical claim.
	// The JWT can contain claims that are NOT in the validator. However, if the
	// JWT contains a list of audiences, the validator must also contain an
	// audience in the list.
	//
	// If the JWT contains timestamp claims such as expiration (exp), issued_at
	// (iat) or not_before (nbf), they will also be validated. validator allows to
	// set a clock skew, to deal with small clock differences among different
	// machines.
	VerifyAndDecode(compact string, validator *Validator) (*VerifiedJWT, error)
}

Verifier is the interface for verifying signed JWTs. See RFC 7519 and RFC 7515. Security guarantees: similar to Verifier.

func NewVerifier

func NewVerifier(handle *keyset.Handle) (Verifier, error)

NewVerifier generates a new instance of the JWT Verifier primitive.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL