Documentation
¶
Index ¶
- Constants
- Variables
- func CheckPassword(password, hash string) bool
- func GenerateHash(password string) (string, error)
- func NewJwt(payload jwt.MapClaims, signingKey []byte, duration time.Duration) (string, error)
- func NewJwtEmailChangeToken(userID, oldEmail, newEmail, passwordHash, secret string, ...) (string, error)
- func NewJwtEmailVerificationToken(userID, email, passwordHash, secret string, duration time.Duration) (string, error)
- func NewJwtPasswordResetToken(userID, email, passwordHash, secret string, duration time.Duration) (string, error)
- func NewJwtSessionToken(userID, email, passwordHash, secret string, duration time.Duration) (string, error)
- func NewJwtSigningKeyWithCredentials(email, passwordHash, secret string) ([]byte, error)
- func Oauth2CodeVerifier() string
- func Oauth2State() string
- func ParseJwt(token string, verificationKey []byte) (jwt.MapClaims, error)
- func ParseJwtUnverified(tokenString string) (jwt.MapClaims, error)
- func RandomString(length int, alphabet string) string
- func S256Challenge(code string) string
- func ValidateEmailChangeClaims(claims jwt.MapClaims) error
- func ValidateEmailVerificationClaims(claims jwt.MapClaims) error
- func ValidatePasswordResetClaims(claims jwt.MapClaims) error
- func ValidateSessionClaims(claims jwt.MapClaims) error
Constants ¶
const ( // MinKeyLength is the minimum required length for JWT signing keys. // 32 bytes (256 bits) is the minimum recommended length for HMAC-SHA256 keys // to provide sufficient security against brute force attacks. MinKeyLength = 32 // JWT claim constants ClaimIssuedAt = "iat" // JWT Issued At claim key ClaimExpiresAt = "exp" // JWT Expiration Time claim key ClaimUserID = "user_id" // JWT User ID claim key // Email verification specific claims ClaimEmail = "email" // Email address being verified ClaimType = "type" // Verification type claim ClaimVerificationValue = "verification" // Value for verification type claim ClaimPasswordResetValue = "password_reset" // Value for password reset type claim ClaimEmailChangeValue = "email_change" // Value for email change type claim ClaimNewEmail = "new_email" // New email address for email change claims // MaxTokenAge is the maximum age a JWT token can be before it's considered too old (7 days in seconds) MaxTokenAge = 7 * 24 * 60 * 60 )
const AlphanumericAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
const Oauth2StateLength = 32
The OAuth2 specification (RFC 6749) doesn’t mandate a specific length. It recommends a random, unguessable string. At least 16 characters, though 32 to 64 characters is common for better uniqueness and security.
const OauthCodeVerifierLength = 43
Defined in RFC 7636 (PKCE). Its length must be between 43 and 128 characters.
const PKCECodeChallengeMethod = "S256"
PKCE code challenge method as defined in RFC 7636
Variables ¶
var ( // ErrJwtTokenExpired is returned when the token has expired ErrJwtTokenExpired = errors.New("token expired") // ErrJwtInvalidToken is returned when the token is invalid ErrJwtInvalidToken = errors.New("invalid token") // ErrInvalidVerificationToken is returned when verification token is invalid ErrInvalidVerificationToken = errors.New("invalid verification token") // ErrJwtInvalidSigningMethod is returned when the signing method is not HS256 ErrJwtInvalidSigningMethod = errors.New("unexpected signing method") // ErrJwtInvalidSecretLength is returned for invalid secret lengths ErrJwtInvalidSecretLength = errors.New("invalid secret length") // ErrInvalidSigningKeyParts is returned when email or password hash are empty ErrInvalidSigningKeyParts = errors.New("invalid signing key parts") // ErrTokenUsedBeforeIssued is returned when a token's "iat" (issued at) claim // is in the future, indicating the token is being used before it was issued ErrTokenUsedBeforeIssued = errors.New("token used before issued") // ErrInvalidClaimFormat is returned when a claim has the wrong type ErrInvalidClaimFormat = errors.New("invalid claim format") // ErrClaimNotFound is returned when a required claim is missing ErrClaimNotFound = errors.New("claim not found") // ErrTokenTooOld is returned when a token's "iat" (issued at) claim // is older than the maximum allowed age (one week) ErrTokenTooOld = errors.New("token too old") )
Functions ¶
func CheckPassword ¶
CheckPassword compares a bcrypt hashed password with its possible plaintext equivalent
func GenerateHash ¶
GenerateHash creates a bcrypt hash from a password using reasonable default cost
func NewJwtEmailChangeToken ¶
func NewJwtEmailChangeToken(userID, oldEmail, newEmail, passwordHash, secret string, duration time.Duration) (string, error)
NewJwtPasswordResetToken creates a JWT specifically for password reset
func NewJwtEmailVerificationToken ¶
func NewJwtEmailVerificationToken(userID, email, passwordHash, secret string, duration time.Duration) (string, error)
NewJwtEmailVerificationToken creates a JWT specifically for email verification It includes additional claims needed for verification
func NewJwtSessionToken ¶
func NewJwtSessionToken(userID, email, passwordHash, secret string, duration time.Duration) (string, error)
NewJwtSession creates a new JWT session token for a user It handles the complete token generation process including: - Creating the signing key from user credentials - Setting up standard claims - Generating and signing the token
func NewJwtSigningKeyWithCredentials ¶
It derives a unique key by combining user-specific data (email, passwordHash) with a server secret (JWT_SECRET). Tokens are invalidated when the user's email or password changes, or globally by rotating JWT_SECRET.
The passwordHash parameter can be empty to support passwordless authentication methods like OAuth2. In this case, the signing key is derived only from the email and server secret.
Using HMAC prevents length-extension attacks, unlike simple hash concatenation.
The function uses a null byte (\x00) as a delimiter to prevent collisions between the email and passwordHash inputs. It returns the key as a byte slice, suitable for use with github.com/golang-jwt/jwt/v5's SignedString method, and an error if the server secret is unset or inputs are invalid.
Note: JWT_SECRET should be a strong, random value (e.g., 32+ bytes).
func Oauth2CodeVerifier ¶
func Oauth2CodeVerifier() string
func Oauth2State ¶
func Oauth2State() string
The state parameter helps prevent Cross-Site Request Forgery (CSRF) attacks by linking the authorization request to its callback. Should be URL-safe, Here alphanumeric characters.
func ParseJwt ¶
ParseJwt verifies and parses JWT and returns its claims. returns a map map[string]any that you can access like any other Go map.
exp := claims["exp"].(float64)
func ParseJwtUnverified ¶
Implement only the validation rather than using the full validator but this is not lightweight either, 60% so expensive as full.
func RandomString ¶
func S256Challenge ¶
S256Challenge creates base64 encoded sha256 challenge string derived from code. The padding of the result base64 string is stripped per RFC 7636.
func ValidateSessionClaims ¶
Types ¶
This section is empty.