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
- Variables
- type ClaimStrings
- type Claims
- type HMAC
- type HMACPrivateKey
- type MockClaims
- type MockClaims_Expecter
- type MockClaims_Valid_Call
- type MockParserOptions
- type MockParserOptions_Execute_Call
- func (_c *MockParserOptions_Execute_Call) Return() *MockParserOptions_Execute_Call
- func (_c *MockParserOptions_Execute_Call) Run(run func(_a0 *Parser[Claims])) *MockParserOptions_Execute_Call
- func (_c *MockParserOptions_Execute_Call) RunAndReturn(run func(*Parser[Claims])) *MockParserOptions_Execute_Call
- type MockParserOptions_Expecter
- type MockSigner
- type MockSigner_Expecter
- type MockSigner_Sign_Call
- func (_c *MockSigner_Sign_Call) Return(signature []byte, err error) *MockSigner_Sign_Call
- func (_c *MockSigner_Sign_Call) Run(run func(rand io.Reader, digest []byte, opts crypto.SignerOpts)) *MockSigner_Sign_Call
- func (_c *MockSigner_Sign_Call) RunAndReturn(run func(io.Reader, []byte, crypto.SignerOpts) ([]byte, error)) *MockSigner_Sign_Call
- type MockSigningMethod
- type MockSigningMethod_Alg_Call
- type MockSigningMethod_Expecter
- func (_e *MockSigningMethod_Expecter) Alg() *MockSigningMethod_Alg_Call
- func (_e *MockSigningMethod_Expecter) Sign(signingString interface{}, key interface{}) *MockSigningMethod_Sign_Call
- func (_e *MockSigningMethod_Expecter) Verify(signingString interface{}, sig interface{}, key interface{}) *MockSigningMethod_Verify_Call
- type MockSigningMethod_Sign_Call
- func (_c *MockSigningMethod_Sign_Call) Return(_a0 []byte, _a1 error) *MockSigningMethod_Sign_Call
- func (_c *MockSigningMethod_Sign_Call) Run(run func(signingString []byte, key Signer)) *MockSigningMethod_Sign_Call
- func (_c *MockSigningMethod_Sign_Call) RunAndReturn(run func([]byte, Signer) ([]byte, error)) *MockSigningMethod_Sign_Call
- type MockSigningMethod_Verify_Call
- func (_c *MockSigningMethod_Verify_Call) Return(_a0 error) *MockSigningMethod_Verify_Call
- func (_c *MockSigningMethod_Verify_Call) Run(run func(signingString []byte, sig []byte, key VerifyKey)) *MockSigningMethod_Verify_Call
- func (_c *MockSigningMethod_Verify_Call) RunAndReturn(run func([]byte, []byte, VerifyKey) error) *MockSigningMethod_Verify_Call
- type MockVerifyKey
- type MockVerifyKey_Expecter
- type Parser
- type ParserOptions
- type RSA
- type RegisteredClaims
- type Signer
- type SigningMethod
- type Token
- type VerifyKey
Constants ¶
const ( SigningMethodNameHS256 string = "HS256" SigningMethodNameHS384 string = "HS384" SigningMethodNameHS512 string = "HS512" )
const ( SigningMethodNameRS256 string = "RS256" SigningMethodNameRS384 string = "RS384" SigningMethodNameRS512 string = "RS512" )
Variables ¶
var ( ErrInvalidKeyType = errors.New("invalid key type") 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 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 ¶
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 ¶
func (_e *MockClaims_Expecter) Valid() *MockClaims_Valid_Call
Valid is a helper method to define mock.On call
type MockClaims_Valid_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 (_c *MockClaims_Valid_Call) Return(_a0 error) *MockClaims_Valid_Call
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 ¶
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 (_m *MockParserOptions) EXPECT() *MockParserOptions_Expecter
func (*MockParserOptions) Execute ¶
func (_m *MockParserOptions) Execute(_a0 *Parser[Claims])
Execute provides a mock function with given fields: _a0
type MockParserOptions_Execute_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 (_c *MockParserOptions_Execute_Call) Return() *MockParserOptions_Execute_Call
func (*MockParserOptions_Execute_Call) Run ¶
func (_c *MockParserOptions_Execute_Call) Run(run func(_a0 *Parser[Claims])) *MockParserOptions_Execute_Call
func (*MockParserOptions_Execute_Call) RunAndReturn ¶
func (_c *MockParserOptions_Execute_Call) RunAndReturn(run func(*Parser[Claims])) *MockParserOptions_Execute_Call
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 ¶
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 ¶
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 ¶
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 (_m *MockSigningMethod) EXPECT() *MockSigningMethod_Expecter
type MockSigningMethod_Alg_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 (_c *MockSigningMethod_Alg_Call) Return(_a0 string) *MockSigningMethod_Alg_Call
func (*MockSigningMethod_Alg_Call) Run ¶
func (_c *MockSigningMethod_Alg_Call) Run(run func()) *MockSigningMethod_Alg_Call
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 ¶
func (_e *MockSigningMethod_Expecter) Alg() *MockSigningMethod_Alg_Call
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 ¶
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 (_c *MockSigningMethod_Sign_Call) Return(_a0 []byte, _a1 error) *MockSigningMethod_Sign_Call
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 ¶
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 (_c *MockSigningMethod_Verify_Call) Return(_a0 error) *MockSigningMethod_Verify_Call
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 ¶
func (_c *MockSigningMethod_Verify_Call) RunAndReturn(run func([]byte, []byte, VerifyKey) error) *MockSigningMethod_Verify_Call
type MockVerifyKey ¶
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 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 ¶
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 ¶
RSA implements the RSA family of signing methods
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