jwt

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2022 License: Apache-2.0 Imports: 24 Imported by: 0

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/google/tink/go/jwt"
	"github.com/google/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 (
	"fmt"
	"log"
	"time"

	"github.com/google/tink/go/jwt"
	"github.com/google/tink/go/keyset"
)

func main() {
	// Generate a private keyset handle.
	handlePriv, err := keyset.NewHandle(jwt.ES256Template())
	if err != nil {
		log.Fatal(err)
	}

	// TODO: Save the private 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

	// Get a public keyset handle from the private keyset handle.
	handlePub, err := handlePriv.Public()
	if err != nil {
		log.Fatal(err)
	}

	// Create and sign a token.
	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)
	}
	signer, err := jwt.NewSigner(handlePriv)
	if err != nil {
		log.Fatal(err)
	}
	token, err := signer.SignAndEncode(rawJWT)
	if err != nil {
		log.Fatal(err)
	}

	// Verify the signed token.
	verifier, err := jwt.NewVerifier(handlePub)
	if err != nil {
		log.Fatal(err)
	}
	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

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 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 and ES512 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 and ES512 are supported. JWK is defined in https://www.rfc-editor.org/rfc/rfc7517.txt.

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.

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(h *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(h *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(h *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