Documentation ¶
Overview ¶
Package jwt provides a simplified and secure API for encoding, decoding and verifying JSON Web Tokens (JWT).
See https://jwt.io/ and https://tools.ietf.org/html/rfc7519
The API is designed to be instantly familiar to users of the standard crypto and json packages:
// create jwt.Signer from a key store rs384 := jwt.RS384.New(myKeyStore()) // create claims claims := jwt.Claims{ Issuer: "user@example.com", } // encode claims as a JWT: buf, err := rs384.Encode(&claims) if err != nil { log.Fatalln(err) } fmt.Printf("token: %s\n", string(buf)) // decode and verify claims: cl2 := jwt.Claims{} err = rs384.Decode(buf, &cl2) if err == jwt.ErrInvalidSignature { // invalid signature } else if err != nil { // handle general error } fmt.Printf("decoded claims: %+v\n", cl2)
Index ¶
- Constants
- Variables
- func Decode(alg Algorithm, signer Signer, buf []byte, obj interface{}) error
- func DecodeUnverifiedToken(buf []byte, ut *UnverifiedToken) error
- func Encode(alg Algorithm, signer Signer, obj interface{}) ([]byte, error)
- func NewEllipticSigner(alg Algorithm, curve elliptic.Curve) func(Store, crypto.Hash) (Signer, error)
- func NewHMACSigner(alg Algorithm) func(Store, crypto.Hash) (Signer, error)
- func NewRSASigner(alg Algorithm, method RSASignerVerifier) func(Store, crypto.Hash) (Signer, error)
- func PeekHeaderField(buf []byte, field string) (string, error)
- func PeekPayloadField(buf []byte, field string) (string, error)
- type Algorithm
- func (alg Algorithm) Decode(signer Signer, buf []byte, obj interface{}) error
- func (alg Algorithm) Encode(signer Signer, obj interface{}) ([]byte, error)
- func (alg Algorithm) Header() Header
- func (alg Algorithm) MarshalText() ([]byte, error)
- func (alg Algorithm) New(keyset interface{}) (Signer, error)
- func (i Algorithm) String() string
- func (alg *Algorithm) UnmarshalText(buf []byte) error
- type Claims
- type EccSigner
- func (s *EccSigner) Decode(buf []byte, obj interface{}) error
- func (s *EccSigner) Encode(obj interface{}) ([]byte, error)
- func (s *EccSigner) Mksig(r, i *big.Int) ([]byte, error)
- func (s *EccSigner) Sign(buf []byte) ([]byte, error)
- func (s *EccSigner) SignBytes(buf []byte) ([]byte, error)
- func (s *EccSigner) Verify(buf, sig []byte) ([]byte, error)
- func (s *EccSigner) VerifyBytes(buf, sig []byte) error
- type Error
- type Header
- type HmacSigner
- func (s *HmacSigner) Decode(buf []byte, obj interface{}) error
- func (s *HmacSigner) Encode(obj interface{}) ([]byte, error)
- func (s *HmacSigner) Sign(buf []byte) ([]byte, error)
- func (s *HmacSigner) SignBytes(buf []byte) ([]byte, error)
- func (s *HmacSigner) Verify(buf, sig []byte) ([]byte, error)
- func (s *HmacSigner) VerifyBytes(buf, sig []byte) error
- type Keystore
- type RSAMethod
- type RSASigner
- func (s *RSASigner) Decode(buf []byte, obj interface{}) error
- func (s *RSASigner) Encode(obj interface{}) ([]byte, error)
- func (s *RSASigner) Sign(buf []byte) ([]byte, error)
- func (s *RSASigner) SignBytes(buf []byte) ([]byte, error)
- func (s *RSASigner) Verify(buf, sig []byte) ([]byte, error)
- func (s *RSASigner) VerifyBytes(buf, sig []byte) error
- type RSASignerVerifier
- type Signer
- type Store
- type Token
- type UnverifiedToken
Constants ¶
const RSAMinimumBitLen = 2048
RSAMinimumBitLen is the minimum accepted RSA key length.
Variables ¶
var RSAMethodPKCS1v15 = RSAMethod{ SignFunc: rsa.SignPKCS1v15, VerifyFunc: rsa.VerifyPKCS1v15, }
RSAMethodPKCS1v15 provides a RSA method that signs and verifies with PKCS1v15.
var RSAMethodPSS = RSAMethod{ SignFunc: func(rand io.Reader, priv *rsa.PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error) { return rsa.SignPSS(rand, priv, hash, hashed, &rsa.PSSOptions{ SaltLength: rsa.PSSSaltLengthAuto, Hash: hash, }) }, VerifyFunc: func(pub *rsa.PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error { return rsa.VerifyPSS(pub, hash, hashed, sig, &rsa.PSSOptions{ SaltLength: rsa.PSSSaltLengthAuto, Hash: hash, }) }, }
RSAMethodPSS provides a RSA method that signs and verifies with PSS.
Functions ¶
func Decode ¶
Decode decodes a serialized JWT in buf into obj, and verifies the JWT signature using the Algorithm and Signer.
If the token or signature is invalid, ErrInvalidToken or ErrInvalidSignature will be returned, respectively. Otherwise, any other errors encountered during token decoding will be returned.
func DecodeUnverifiedToken ¶
func DecodeUnverifiedToken(buf []byte, ut *UnverifiedToken) error
DecodeUnverifiedToken decodes a token into the provided UnverifiedToken.
func Encode ¶
Encode encodes a JWT using the Algorithm and Signer, returning the URL-safe encoded token or any errors encountered during encoding.
func NewEllipticSigner ¶
func NewEllipticSigner(alg Algorithm, curve elliptic.Curve) func(Store, crypto.Hash) (Signer, error)
NewEllipticSigner creates an Elliptic Curve Signer for the specified curve.
func NewHMACSigner ¶
NewHMACSigner creates a HMAC Signer for the specified Algorithm.
func NewRSASigner ¶
NewRSASigner creates an RSA Signer for the specified Algorithm and provided low level RSA implementation.
func PeekHeaderField ¶
PeekHeaderField extracts the specified field from the serialized JWT buf's header. An error will be returned if the field is not present in the decoded header.
Types ¶
type Algorithm ¶
type Algorithm uint
Algorithm is the type for signing algorithms implemented in this package.
const ( // NONE provides a JWT signing method for NONE. // // NOTE: This is not implemented for security reasons. NONE Algorithm = iota // HS256 provides a JWT signing method for HMAC using SHA-256. // // See http://tools.ietf.org/html/rfc7518#section-3.2 HS256 // HS384 provides a JWT signing method for HMAC using SHA-384. // // See http://tools.ietf.org/html/rfc7518#section-3.2 HS384 // HS512 provides a JWT signing method for HMAC using SHA-512. // // See http://tools.ietf.org/html/rfc7518#section-3.2 HS512 // RS256 provides a JWT signing method for RSASSA-PKCS1-V1_5 using SHA-256. // // See http://tools.ietf.org/html/rfc7518#section-3.3 RS256 // RS384 provides a JWT signing method for RSASSA-PKCS1-V1_5 using SHA-384. // // See http://tools.ietf.org/html/rfc7518#section-3.3 RS384 // RS512 provides a JWT signing method for RSASSA-PKCS1-V1_5 using SHA-512. // // See http://tools.ietf.org/html/rfc7518#section-3.3 RS512 // ES256 provides a JWT signing method for ECDSA using P-256 and SHA-256. // // See http://tools.ietf.org/html/rfc7518#section-3.4 ES256 // ES384 provides a JWT signing method for ECDSA using P-384 and SHA-384. // // See http://tools.ietf.org/html/rfc7518#section-3.4 ES384 // ES512 provides a JWT signing method for ECDSA using P-521 and SHA-512. // // See http://tools.ietf.org/html/rfc7518#section-3.4 ES512 // PS256 provides a JWT signing method for RSASSA-PSS using SHA-256 and // MGF1 mask generation function with SHA-256. // // See http://tools.ietf.org/html/rfc7518#section-3.5 PS256 // PS384 provides a JWT signing method for RSASSA-PSS using SHA-384 hash // algorithm and MGF1 mask generation function with SHA-384. // // See http://tools.ietf.org/html/rfc7518#section-3.5 PS384 // PS512 provides a JWT signing method for RSASSA-PSS using SHA-512 hash // algorithm and MGF1 mask generation function with SHA-512. // // See http://tools.ietf.org/html/rfc7518#section-3.5 PS512 )
func PeekAlgorithm ¶
PeekAlgorithm extracts the signing algorithm listed in the "alg" field of the serialized JWT buf's header and attempts to unmarshal it into an Algorithm. An error will be returned if the alg field is not specified in the JWT header, or is otherwise invalid.
func PeekAlgorithmAndIssuer ¶
PeekAlgorithmAndIssuer extracts the signing algorithm listed in the "alg" field and the issuer from the "iss" field of the serialized JWT buf's header and payload, attempting to unmarshal alg to Algorithm and iss to a string. An error will be returned if the Algorithm or Issuer fields are not specified in the JWT header and payload, or are otherwise invalid.
func (Algorithm) Decode ¶
Decode decodes a serialized JWT in buf into obj, and verifies the JWT signature using the Algorithm and Signer.
If the token or signature is invalid, ErrInvalidToken or ErrInvalidSignature will be returned, respectively. Otherwise, any other errors encountered during token decoding will be returned.
func (Algorithm) MarshalText ¶
MarshalText marshals Algorithm into a serialized form.
func (Algorithm) New ¶
New creates a Signer using the supplied keyset.
The keyset can be of type []byte, *rsa.{PrivateKey,PublicKey}, *ecdsa.{PrivateKey,PublicKey}, or compatible with the Store interface.
If a private key is not provided, tokens cannot be Encode'd. Public keys will be automatically generated for RSA and ECC private keys if none were provided in the keyset.
func (*Algorithm) UnmarshalText ¶
UnmarshalText attempts to unmarshal buf into an Algorithm.
type Claims ¶
type Claims struct { // Issuer ("iss") identifies the principal that issued the JWT. Issuer string `json:"iss,omitempty"` // Subject ("sub") identifies the principal that is the subject of the JWT. Subject string `json:"sub,omitempty"` // Audience ("aud") identifies the recipients that the JWT is intended for. Audience string `json:"aud,omitempty"` // Expiration ("exp") identifies the expiration time on or after which the // JWT MUST NOT be accepted for processing. Expiration json.Number `json:"exp,omitempty"` // NotBefore ("nbf") identifies the time before which the JWT MUST NOT be // accepted for processing. NotBefore json.Number `json:"nbf,omitempty"` // IssuedAt ("iat") identifies the time at which the JWT was issued. IssuedAt json.Number `json:"iat,omitempty"` // JwtID ("jti") provides a unique identifier for the JWT. JwtID string `json:"jti,omitempty"` }
Claims contains the registered JWT claims.
type EccSigner ¶
type EccSigner struct {
// contains filtered or unexported fields
}
EccSigner provides an Elliptic Curve Signer.
func (*EccSigner) Decode ¶
Decode decodes a serialized token, verifying the signature, storing the decoded data from the token in obj.
func (*EccSigner) Mksig ¶
Mksig creates a byte slice of length 2*keyLen, copying the bytes from r and s into the slice, left padding r and i to keyLen.
func (*EccSigner) Sign ¶
Sign creates a signature for buf, returning it as a URL-safe base64 encoded byte slice.
func (*EccSigner) Verify ¶
Verify creates a signature for buf, comparing it against the URL-safe base64 encoded sig and returning the decoded signature. If the sig is invalid, then ErrInvalidSignature will be returned.
func (*EccSigner) VerifyBytes ¶
VerifyBytes creates a signature for buf, comparing it against the raw sig. If the sig is invalid, then ErrInvalidSignature is returned.
type Error ¶
type Error string
Error is a jwt error.
const ( // ErrInvalidSignature is the invalid signature error. ErrInvalidSignature Error = "invalid signature" // ErrInvalidAlgorithm is the invalid algorithm error. ErrInvalidAlgorithm Error = "invalid algorithm" // ErrInvalidToken is the invalid token error. ErrInvalidToken Error = "invalid token" // ErrInvalidKeyset is the invalid keyset error. ErrInvalidKeyset Error = "invalid keyset" // ErrInvalidHash is the invalid hash error. ErrInvalidHash Error = "invalid hash" // ErrMissingPrivateKey is the missing private key error. ErrMissingPrivateKey Error = "missing private key" // ErrMissingPublicKey is the missing public key error. ErrMissingPublicKey Error = "missing public key" // ErrMissingPrivateOrPublicKey is the missing private or public key error. ErrMissingPrivateOrPublicKey Error = "missing private or public key" // ErrInvalidPrivateKey is the invalid private key error. ErrInvalidPrivateKey Error = "invalid private key" // ErrInvalidPublicKey is the invalid public key error. ErrInvalidPublicKey Error = "invalid public key" // ErrInvalidPrivateKeySize is the invalid private key size error. ErrInvalidPrivateKeySize Error = "invalid private key size" // ErrMismatchedBytesCopied is the mismatched bytes copied error. ErrMismatchedBytesCopied Error = "mismatched bytes copied" // ErrInvalidPublicKeySize is the invalid public key size error. ErrInvalidPublicKeySize Error = "invalid public key size" )
Error values.
type HmacSigner ¶
type HmacSigner struct {
// contains filtered or unexported fields
}
HmacSigner provides a HMAC Signer.
func (*HmacSigner) Decode ¶
func (s *HmacSigner) Decode(buf []byte, obj interface{}) error
Decode decodes a serialized token, verifying the signature, storing the decoded data from the token in obj.
func (*HmacSigner) Encode ¶
func (s *HmacSigner) Encode(obj interface{}) ([]byte, error)
Encode serializes the JSON marshalable obj data as a JWT.
func (*HmacSigner) Sign ¶
func (s *HmacSigner) Sign(buf []byte) ([]byte, error)
Sign creates a signature for buf, returning it as a URL-safe base64 encoded byte slice.
func (*HmacSigner) SignBytes ¶
func (s *HmacSigner) SignBytes(buf []byte) ([]byte, error)
SignBytes creates a signature for buf.
func (*HmacSigner) Verify ¶
func (s *HmacSigner) Verify(buf, sig []byte) ([]byte, error)
Verify creates a signature for buf, comparing it against the URL-safe base64 encoded sig and returning the decoded signature. If the sig is invalid, then ErrInvalidSignature will be returned.
func (*HmacSigner) VerifyBytes ¶
func (s *HmacSigner) VerifyBytes(buf, sig []byte) error
VerifyBytes creates a signature for buf, comparing it against the raw sig. If the sig is invalid, then ErrInvalidSignature is returned.
type Keystore ¶
type Keystore struct { // Key is the private key. Key interface{} // PublicKey is the public key. PubKey interface{} // contains filtered or unexported fields }
Keystore is a simple type providing a Store implementation.
func (*Keystore) PrivateKey ¶
func (s *Keystore) PrivateKey() (crypto.PrivateKey, bool)
PrivateKey returns the stored private key for the keystore.
type RSAMethod ¶
type RSAMethod struct { SignFunc func(io.Reader, *rsa.PrivateKey, crypto.Hash, []byte) ([]byte, error) VerifyFunc func(*rsa.PublicKey, crypto.Hash, []byte, []byte) error }
RSAMethod provides a wrapper for rsa signing methods.
type RSASigner ¶
type RSASigner struct {
// contains filtered or unexported fields
}
RSASigner provides a RSA Signer.
func (*RSASigner) Decode ¶
Decode decodes a serialized token, verifying the signature, storing the decoded data from the token in obj.
func (*RSASigner) Sign ¶
Sign creates a signature for buf, returning it as a URL-safe base64 encoded byte slice.
func (*RSASigner) Verify ¶
Verify creates a signature for buf, comparing it against the URL-safe base64 encoded sig and returning the decoded signature. If the sig is invalid, then ErrInvalidSignature will be returned.
func (*RSASigner) VerifyBytes ¶
VerifyBytes creates a signature for buf, comparing it against the raw sig. If the sig is invalid, then ErrInvalidSignature is returned.
type RSASignerVerifier ¶
type RSASignerVerifier interface { // Sign signs data in buf using rand, priv and hash. Sign(rand io.Reader, priv *rsa.PrivateKey, hash crypto.Hash, buf []byte) ([]byte, error) // Verify verifies the signature sig against using pub, hash, and the // hashed data. Verify(pub *rsa.PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error }
RSASignerVerifier provides a standardized interface to low level RSA signing implementation.
This is used internally to provide a common interface to the RSA Sign/Verify implementations for PKCS1v15 and PSS.
type Signer ¶
type Signer interface { // SignBytes creates a signature for buf. SignBytes(buf []byte) ([]byte, error) // Sign creates a signature for buf, returning it as a URL-safe base64 // encoded byte slice. Sign(buf []byte) ([]byte, error) // VerifyBytes creates a signature for buf, comparing it against the raw // sig. If the sig is invalid, then ErrInvalidSignature is returned. VerifyBytes(buf, dec []byte) error // Verify creates a signature for buf, comparing it against the URL-safe // base64 encoded sig and returning the decoded signature. If the sig is // invalid, then ErrInvalidSignature will be returned. Verify(buf, sig []byte) ([]byte, error) // Encode encodes obj as a serialized JWT. Encode(obj interface{}) ([]byte, error) // Decode decodes a serialized JWT in buf into obj, and verifying the JWT // signature in the process. Decode(buf []byte, obj interface{}) error }
Signer is the shared interface for an Algorithm's encoding, decoding, signing, and verify to handle the crypto primitives and lower-level API calls.
type Store ¶
type Store interface { // PublicKey returns the public key for a store. PublicKey() (crypto.PublicKey, bool) // PrivateKey returns the private key for a store. PrivateKey() (crypto.PrivateKey, bool) }
Store is the common interface for a keystore.
type Token ¶
type Token struct { Header Header `jwt:"header"` Payload Claims `jwt:"payload"` Signature []byte `jwt:"signature"` }
Token is a JWT token, comprising header, payload (ie, claims), and signature.
type UnverifiedToken ¶
type UnverifiedToken struct {
Header, Payload, Signature []byte
}
UnverifiedToken is a token split into its composite parts, but has not yet been decoded, nor verified.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
_example/main.go
|
_example/main.go |
Package bearer provides a generic oauth2.TokenSource for JWT Bearer Grant Assertions.
|
Package bearer provides a generic oauth2.TokenSource for JWT Bearer Grant Assertions. |
cmd
|
|
gurl
Command gurl signs URLs using Google Service Account credentials for use with Google Storage.
|
Command gurl signs URLs using Google Service Account credentials for use with Google Storage. |
Package gserviceaccount provides a simple way to load Google service account credentials and create a corresponding oauth2.TokenSource from it.
|
Package gserviceaccount provides a simple way to load Google service account credentials and create a corresponding oauth2.TokenSource from it. |
Package url provides a quick API to sign Google Storage URLs using Google Service Account Credentials.
|
Package url provides a quick API to sign Google Storage URLs using Google Service Account Credentials. |