A comprehensive Go implementation of JSON Web Tokens (JWT) as specified in RFC 7519. This library enables developers to create, parse, verify, sign, and validate JWTs for authentication and authorization purposes.
go get -u github.com/golang-jwt/jwt/v5import "github.com/golang-jwt/jwt/v5"For HTTP request extraction utilities:
import "github.com/golang-jwt/jwt/v5/request"import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
// Create claims
claims := jwt.RegisteredClaims{
Issuer: "my-app",
Subject: "user123",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
}
// Create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign token with secret key
secretKey := []byte("my-secret-key")
signedToken, err := token.SignedString(secretKey)
if err != nil {
panic(err)
}
fmt.Println("Signed token:", signedToken)import (
"fmt"
"github.com/golang-jwt/jwt/v5"
)
// Parse and validate token
tokenString := "eyJhbGc..."
secretKey := []byte("my-secret-key")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Validate the signing method
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return secretKey, nil
})
if err != nil {
panic(err)
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Println("Token is valid!")
fmt.Println("Claims:", claims)
}The JWT library is organized into several key components:
Create JWT tokens with various claims types and sign them using multiple algorithms including HMAC, RSA, RSA-PSS, ECDSA, and EdDSA.
func New(method SigningMethod, opts ...TokenOption) *Token
func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *TokenParse JWT token strings, validate signatures, and verify claims with comprehensive validation options.
func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error)
func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error)Handle JWT claims using structured RegisteredClaims or flexible MapClaims, with support for custom claims implementations.
type Claims interface {
GetExpirationTime() (*NumericDate, error)
GetIssuedAt() (*NumericDate, error)
GetNotBefore() (*NumericDate, error)
GetIssuer() (string, error)
GetSubject() (string, error)
GetAudience() (ClaimStrings, error)
}
type RegisteredClaims struct {
Issuer string
Subject string
Audience ClaimStrings
ExpiresAt *NumericDate
NotBefore *NumericDate
IssuedAt *NumericDate
ID string
}
type MapClaims map[string]anySupport for multiple signing algorithms with pre-configured instances for each algorithm variant.
type SigningMethod interface {
Verify(signingString string, sig []byte, key any) error
Sign(signingString string, key any) ([]byte, error)
Alg() string
}Available algorithms:
Signing Methods and Algorithms
Parse cryptographic keys from PEM-encoded formats for use with signing and verification.
func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)
func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error)
func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error)
func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error)
func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error)Extract JWT tokens from HTTP requests using various strategies including Authorization headers, query parameters, and custom extractors.
func ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc, options ...ParseFromRequestOption) (token *jwt.Token, err error)
type Extractor interface {
ExtractToken(*http.Request) (string, error)
}The library provides comprehensive error types for different failure scenarios:
var (
ErrInvalidKey error
ErrInvalidKeyType error
ErrHashUnavailable error
ErrTokenMalformed error
ErrTokenUnverifiable error
ErrTokenSignatureInvalid error
ErrTokenRequiredClaimMissing error
ErrTokenInvalidAudience error
ErrTokenExpired error
ErrTokenUsedBeforeIssued error
ErrTokenInvalidIssuer error
ErrTokenInvalidSubject error
ErrTokenNotValidYet error
ErrTokenInvalidId error
ErrTokenInvalidClaims error
ErrInvalidType error
)Control the precision of timestamps in JWT tokens:
var TimePrecision time.DurationDefault: time.Second (no fractional timestamps)
Control how single-element audience arrays are serialized:
var MarshalSingleStringAsArray boolDefault: true (always serialize as array)