jwt

package
v0.0.0-...-c5966c3 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2025 License: Apache-2.0 Imports: 17 Imported by: 2

Documentation

Overview

Package jwt provided method for signing and verify JWT

Supported signing methods: RSA, HMAC, ECDSA

Usage example:

func main() {
	// This jwt using RSA signing method
	signingMethod := jwt.NewRS256()
	exp := time.Now().UTC().Add(72 * time.Hour).Unix()

	// Create a RSA private key for sign token
	privateKey, err := rsa.GenerateKey(rand.Reader, 4096)
	if err != nil {
		log.Fatal(err)
	}

	var payload jwt.Claims
	payload = jwt.RegisteredClaims{
		Issuer:    "https://limitless.mukagen.com",
		Audience:  []string{"https://resource-api.com"},
		ExpiresAt: &exp,
	}

	// Create a new token with provided signing method and payload, and sign it with the private key
	tokenString, err := jwt.NewToken(signingMethod, payload).SignedString(privateKey)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("JWT: %s\n", tokenString)

	tokenBody := strings.Split(tokenString, ".")[1]
	claims, err := base64.RawURLEncoding.DecodeString(tokenBody)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Claims: %s\n", claims)

	// Parse and verify the token
	tk, err := jwt.NewParser[jwt.RegisteredClaims]().Parse(tokenString, func(_ string) (crypto.PublicKey, error) {
		return privateKey.Public(), nil
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Token: %+v\n", tk)
}

Index

Constants

View Source
const (
	SigningMethodNameHS256 string = "HS256"
	SigningMethodNameHS384 string = "HS384"
	SigningMethodNameHS512 string = "HS512"
)
View Source
const (
	SigningMethodNameRS256 string = "RS256"
	SigningMethodNameRS384 string = "RS384"
	SigningMethodNameRS512 string = "RS512"
)

Variables

View Source
var (
	ErrInvalidKeyType = errors.New("invalid key type")

	ErrHashUnavailable = errors.New("unavailable hash function")

	ErrTokenMalformed = errors.New("malformed token")

	ErrInvalidToken = errors.New("invalid token")

	ErrSigningMethodNotSupported = errors.New("signing method not supported")

	ErrInvalidSignature = errors.New("invalid signature")

	ErrMissingRequiredClaim = errors.New("missing required claim in token")

	ErrTokenExpired = errors.New("token is expired")

	ErrTokenUsedBeforeIssued = errors.New("token is used before issued")

	ErrTokenNotValidYet = errors.New("token is not valid yet")
)

Functions

This section is empty.

Types

type ClaimStrings

type ClaimStrings []string

ClaimStrings represents a claim's value as a slice of strings

func (*ClaimStrings) MarshalJSON

func (c *ClaimStrings) MarshalJSON() ([]byte, error)

func (*ClaimStrings) UnmarshalJSON

func (c *ClaimStrings) UnmarshalJSON(data []byte) error

type Claims

type Claims interface {
	Valid() error
}

Claims represent any form of a JWT Claims

type HMAC

type HMAC struct {
	Name string
	Hash crypto.Hash
}

func NewHS256

func NewHS256() HMAC

func NewHS384

func NewHS384() HMAC

func NewHS512

func NewHS512() HMAC

func (HMAC) Alg

func (sm HMAC) Alg() string

func (HMAC) Sign

func (sm HMAC) Sign(signingString []byte, key Signer) ([]byte, error)

func (HMAC) Verify

func (sm HMAC) Verify(signingString []byte, sig []byte, key VerifyKey) error

type HMACPrivateKey

type HMACPrivateKey []byte

HMACPrivateKey represents private key for HMAC signing method

func (HMACPrivateKey) Sign

func (h HMACPrivateKey) Sign(rand io.Reader, signingString []byte, opts crypto.SignerOpts) ([]byte, error)

type MockClaims

type MockClaims struct {
	mock.Mock
}

MockClaims is an autogenerated mock type for the Claims type

func NewMockClaims

func NewMockClaims(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockClaims

NewMockClaims creates a new instance of MockClaims. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockClaims) EXPECT

func (_m *MockClaims) EXPECT() *MockClaims_Expecter

func (*MockClaims) Valid

func (_m *MockClaims) Valid() error

Valid provides a mock function with no fields

type MockClaims_Expecter

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

func (*MockClaims_Expecter) Valid

Valid is a helper method to define mock.On call

type MockClaims_Valid_Call

type MockClaims_Valid_Call struct {
	*mock.Call
}

MockClaims_Valid_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Valid'

func (*MockClaims_Valid_Call) Return

func (*MockClaims_Valid_Call) Run

func (_c *MockClaims_Valid_Call) Run(run func()) *MockClaims_Valid_Call

func (*MockClaims_Valid_Call) RunAndReturn

func (_c *MockClaims_Valid_Call) RunAndReturn(run func() error) *MockClaims_Valid_Call

type MockParserOptions

type MockParserOptions struct {
	mock.Mock
}

MockParserOptions is an autogenerated mock type for the ParserOptions type

func NewMockParserOptions

func NewMockParserOptions(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockParserOptions

NewMockParserOptions creates a new instance of MockParserOptions. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockParserOptions) EXPECT

func (*MockParserOptions) Execute

func (_m *MockParserOptions) Execute(_a0 *Parser[Claims])

Execute provides a mock function with given fields: _a0

type MockParserOptions_Execute_Call

type MockParserOptions_Execute_Call struct {
	*mock.Call
}

MockParserOptions_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute'

func (*MockParserOptions_Execute_Call) Return

func (*MockParserOptions_Execute_Call) Run

func (*MockParserOptions_Execute_Call) RunAndReturn

type MockParserOptions_Expecter

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

func (*MockParserOptions_Expecter) Execute

func (_e *MockParserOptions_Expecter) Execute(_a0 interface{}) *MockParserOptions_Execute_Call

Execute is a helper method to define mock.On call

  • _a0 *Parser[Claims]

type MockSigner

type MockSigner struct {
	mock.Mock
}

MockSigner is an autogenerated mock type for the Signer type

func NewMockSigner

func NewMockSigner(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockSigner

NewMockSigner creates a new instance of MockSigner. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockSigner) EXPECT

func (_m *MockSigner) EXPECT() *MockSigner_Expecter

func (*MockSigner) Sign

func (_m *MockSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)

Sign provides a mock function with given fields: rand, digest, opts

type MockSigner_Expecter

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

func (*MockSigner_Expecter) Sign

func (_e *MockSigner_Expecter) Sign(rand interface{}, digest interface{}, opts interface{}) *MockSigner_Sign_Call

Sign is a helper method to define mock.On call

  • rand io.Reader
  • digest []byte
  • opts crypto.SignerOpts

type MockSigner_Sign_Call

type MockSigner_Sign_Call struct {
	*mock.Call
}

MockSigner_Sign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Sign'

func (*MockSigner_Sign_Call) Return

func (_c *MockSigner_Sign_Call) Return(signature []byte, err error) *MockSigner_Sign_Call

func (*MockSigner_Sign_Call) Run

func (_c *MockSigner_Sign_Call) Run(run func(rand io.Reader, digest []byte, opts crypto.SignerOpts)) *MockSigner_Sign_Call

func (*MockSigner_Sign_Call) RunAndReturn

func (_c *MockSigner_Sign_Call) RunAndReturn(run func(io.Reader, []byte, crypto.SignerOpts) ([]byte, error)) *MockSigner_Sign_Call

type MockSigningMethod

type MockSigningMethod struct {
	mock.Mock
}

MockSigningMethod is an autogenerated mock type for the SigningMethod type

func NewMockSigningMethod

func NewMockSigningMethod(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockSigningMethod

NewMockSigningMethod creates a new instance of MockSigningMethod. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockSigningMethod) Alg

func (_m *MockSigningMethod) Alg() string

Alg provides a mock function with no fields

func (*MockSigningMethod) EXPECT

func (*MockSigningMethod) Sign

func (_m *MockSigningMethod) Sign(signingString []byte, key Signer) ([]byte, error)

Sign provides a mock function with given fields: signingString, key

func (*MockSigningMethod) Verify

func (_m *MockSigningMethod) Verify(signingString []byte, sig []byte, key VerifyKey) error

Verify provides a mock function with given fields: signingString, sig, key

type MockSigningMethod_Alg_Call

type MockSigningMethod_Alg_Call struct {
	*mock.Call
}

MockSigningMethod_Alg_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Alg'

func (*MockSigningMethod_Alg_Call) Return

func (*MockSigningMethod_Alg_Call) Run

func (*MockSigningMethod_Alg_Call) RunAndReturn

func (_c *MockSigningMethod_Alg_Call) RunAndReturn(run func() string) *MockSigningMethod_Alg_Call

type MockSigningMethod_Expecter

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

func (*MockSigningMethod_Expecter) Alg

Alg is a helper method to define mock.On call

func (*MockSigningMethod_Expecter) Sign

func (_e *MockSigningMethod_Expecter) Sign(signingString interface{}, key interface{}) *MockSigningMethod_Sign_Call

Sign is a helper method to define mock.On call

  • signingString []byte
  • key Signer

func (*MockSigningMethod_Expecter) Verify

func (_e *MockSigningMethod_Expecter) Verify(signingString interface{}, sig interface{}, key interface{}) *MockSigningMethod_Verify_Call

Verify is a helper method to define mock.On call

  • signingString []byte
  • sig []byte
  • key VerifyKey

type MockSigningMethod_Sign_Call

type MockSigningMethod_Sign_Call struct {
	*mock.Call
}

MockSigningMethod_Sign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Sign'

func (*MockSigningMethod_Sign_Call) Return

func (*MockSigningMethod_Sign_Call) Run

func (_c *MockSigningMethod_Sign_Call) Run(run func(signingString []byte, key Signer)) *MockSigningMethod_Sign_Call

func (*MockSigningMethod_Sign_Call) RunAndReturn

func (_c *MockSigningMethod_Sign_Call) RunAndReturn(run func([]byte, Signer) ([]byte, error)) *MockSigningMethod_Sign_Call

type MockSigningMethod_Verify_Call

type MockSigningMethod_Verify_Call struct {
	*mock.Call
}

MockSigningMethod_Verify_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Verify'

func (*MockSigningMethod_Verify_Call) Return

func (*MockSigningMethod_Verify_Call) Run

func (_c *MockSigningMethod_Verify_Call) Run(run func(signingString []byte, sig []byte, key VerifyKey)) *MockSigningMethod_Verify_Call

func (*MockSigningMethod_Verify_Call) RunAndReturn

type MockVerifyKey

type MockVerifyKey struct {
	mock.Mock
}

MockVerifyKey is an autogenerated mock type for the VerifyKey type

func NewMockVerifyKey

func NewMockVerifyKey(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockVerifyKey

NewMockVerifyKey creates a new instance of MockVerifyKey. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockVerifyKey) EXPECT

func (_m *MockVerifyKey) EXPECT() *MockVerifyKey_Expecter

type MockVerifyKey_Expecter

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

type Parser

type Parser[T Claims] struct {
	// contains filtered or unexported fields
}

Parser is a generic struct for parsing and validating JWT strings. T represents a specific Claims type to ensure precise handling of predefined claims.

func NewDefaultParser

func NewDefaultParser[T Claims]() Parser[T]

func NewParser

func NewParser[T Claims](opts ...ParserOptions) Parser[T]

NewParser creates a new Parser with the default signing methods and validator.

func (Parser[T]) Parse

func (p Parser[T]) Parse(tokenString string, getKeyFunc func(string) (crypto.PublicKey, error)) (Token[T], error)

Parse decodes the provided JWT string into a Token, verifies its signature using the provided public key. The public key can be determined dynamically based on the `kid` (Key ID) in the token header.

type ParserOptions

type ParserOptions func(*Parser[Claims])

func WithSigningMethod

func WithSigningMethod(method SigningMethod) ParserOptions

WithSigningMethod add more signing method to parser

func WithSigningMethods

func WithSigningMethods(signingMethods map[string]SigningMethod) ParserOptions

WithSigningMethods overrides all current supported signing methods

type RSA

type RSA struct {
	Name string
	Hash crypto.Hash
}

RSA implements the RSA family of signing methods

func NewRS256

func NewRS256() RSA

NewRS256 creates a new RS256 signing method struct

func NewRS384

func NewRS384() RSA

NewRS384 creates a new RS256 signing method struct

func NewRS512

func NewRS512() RSA

NewRS512 creates a new RS256 signing method struct

func (RSA) Alg

func (sm RSA) Alg() string

func (RSA) Sign

func (sm RSA) Sign(signingString []byte, key Signer) ([]byte, error)

Sign implements token signing for the SigningMethod, that take Signer (*rsa.PrivateKey) for sign a token

func (RSA) Verify

func (sm RSA) Verify(signingString []byte, sig []byte, key VerifyKey) error

Verify verifies the signingString with signature by provided VerifyKey, that can consider as *rsa.PublicKey

type RegisteredClaims

type RegisteredClaims struct {
	Issuer string `json:"iss,omitempty"`

	Subject string `json:"sub,omitempty"`

	Audience ClaimStrings `json:"aud,omitempty"`

	IssuedAt *int64 `json:"iat,omitempty"`

	ExpiresAt *int64 `json:"exp,omitempty"`

	NotBefore *int64 `json:"nbf,omitempty"`

	JTI string `json:"jti,omitempty"`

	ClientID string `json:"client_id,omitempty"`
}

RegisteredClaims represents standard JWT claims More info: https://datatracker.ietf.org/doc/html/rfc7519#section-4.1

func (RegisteredClaims) Valid

func (c RegisteredClaims) Valid() error

Valid validates time based claims "exp, iat, nbf" if any of the above claims are not in the token, it will still be considered a valid claim.

type Signer

type Signer interface {
	Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error)
}

Signer represents an interface for creating digital signatures

type SigningMethod

type SigningMethod interface {
	// Verify returns nil if signature is valid
	Verify(signingString []byte, sig []byte, key VerifyKey) error

	// Sign returns signature or error
	Sign(signingString []byte, key Signer) ([]byte, error)

	// Alg returns the alg identifier for this method (example: 'RS256')
	Alg() string
}

SigningMethod can be used add new methods for signing or verifying tokens. It takes a decoded signature as an input in the Verify function and produces a signature in Sign. The signature is then usually base64 encoded as part of a JWT.

type Token

type Token[T Claims] struct {
	Header    map[string]string
	Claims    T
	Signature []byte
	// contains filtered or unexported fields
}

Token represents a JWT Token

func NewToken

func NewToken[T Claims](method SigningMethod, claims T) Token[T]

NewToken creates a new Token with the specified signing method and claims

func (Token[T]) SignedString

func (tk Token[T]) SignedString(key crypto.Signer) (string, error)

SignedString creates and returns a complete, signed JWT. The token is signed using the SigningMethod specified in the token

type VerifyKey

type VerifyKey interface{}

VerifyKey represents a key for verify token

Jump to

Keyboard shortcuts

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