sjwt

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2025 License: MIT Imports: 10 Imported by: 12

README

alt text

sjwt Go Report Card GoDoc license

Buy Me A Coffee

Simple JSON Web Token - Uses HMAC SHA-256

Minimalistic and efficient tool for handling JSON Web Tokens in Go applications. It offers a straightforward approach to integrating JWT for authentication and security, designed for ease of use.

Features

  • Easy JWT for Go: Implement JWT in Go with minimal effort.
  • Secure & Simple: Reliable security features, easy to integrate.
  • Open Source: MIT licensed, open for community contributions.

Install

Security note: Generate and Verify require secrets that are at least 32 random bytes. Generate keys with crypto/rand (for example hex.EncodeToString) rather than hard-coding test values in production.

go get -u github.com/brianvoe/sjwt

Example

// Set Claims
claims := sjwt.New()
claims.Set("username", "billymister")
claims.Set("account_id", 8675309)

// Generate jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
jwt, err := claims.Generate(secretKey)
if err != nil {
    panic(err)
}

Example parse

secretKey := []byte("0123456789abcdef0123456789abcdef")

// Create a token
claims := sjwt.New()
claims.Set("name", "John Doe")
jwt, err := claims.Generate(secretKey)
if err != nil {
    panic(err)
}

// Parse jwt (no signature verification yet)
parsed, err := sjwt.Parse(jwt)
if err != nil {
    panic(err)
}

// Get claims
name, err := parsed.GetStr("name") // John Doe

Example verify and validate

secretKey := []byte("0123456789abcdef0123456789abcdef")

// Create a token
claims := sjwt.New()
claims.Set("name", "John Doe")
jwt, err := claims.Generate(secretKey)
if err != nil {
    panic(err)
}

// Verify the signature before trusting the payload
if !sjwt.Verify(jwt, secretKey) {
    panic("signature mismatch")
}

// Parse the payload
parsedClaims, err := sjwt.Parse(jwt)
if err != nil {
    panic(err)
}

// Validate will check(if set) Expiration At and Not Before At dates
if err := parsedClaims.Validate(); err != nil {
    panic(err)
}

Example usage of registered claims

// Set Claims
claims := sjwt.New()
claims.SetTokenID()                                  // UUID generated
claims.SetSubject("Subject Title")                   // Subject of the token
claims.SetIssuer("Google")                           // Issuer of the token
claims.SetAudience([]string{"Google", "Facebook"})   // Audience the toke is for
claims.SetIssuedAt(time.Now())                       // IssuedAt in time, value is set in unix
claims.SetNotBeforeAt(time.Now().Add(time.Hour * 1)) // Token valid in 1 hour
claims.SetExpiresAt(time.Now().Add(time.Hour * 24))  // Token expires in 24 hours

// Generate jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
jwt, err := claims.Generate(secretKey)
if err != nil {
    panic(err)
}

Example usage of struct to claims

type Info struct {
    Name string `json:"name"`
}

// Marshal your struct into claims
info := Info{Name: "Billy Mister"}
claims, err := sjwt.ToClaims(info)
if err != nil {
    panic(err)
}

// Generate jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
jwt, err := claims.Generate(secretKey)
if err != nil {
    panic(err)
}

Why?

For all the times I have needed the use of a jwt, its always been a simple HMAC SHA-256 and thats normally the use of most jwt tokens.

Documentation

Overview

Example
// Add Claims
claims := New()
claims.Set("username", "billymister")
claims.Set("account_id", 8675309)

// Generate jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
jwt, err := claims.Generate(secretKey)
if err != nil {
	panic(err)
}
fmt.Println(jwt)
Example (ClaimsToStruct)
type Info struct {
	Name string `json:"name"`
}

// Create jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
claims := New()
claims.Set("name", "Billy Mister")

jwt, err := claims.Generate(secretKey)
if err != nil {
	panic(err)
}

// Parse jwt
parsed, err := Parse(jwt)
if err != nil {
	panic(err)
}

// Marshal your struct into claims
info := Info{}
if err := parsed.ToStruct(&info); err != nil {
	panic(err)
}

name, _ := parsed.GetStr("name")
fmt.Println(name)
Output:

Billy Mister
Example (Parse)
// Create jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
claims := New()
claims.Set("name", "John Doe")

jwt, err := claims.Generate(secretKey)
if err != nil {
	panic(err)
}

// Parse jwt (signature still needs to be verified separately)
parsed, err := Parse(jwt)
if err != nil {
	panic(err)
}

// Get claims
name, _ := parsed.GetStr("name")
fmt.Println(name)
Output:

John Doe
Example (Parse_roundTrip)
secretKey := []byte("0123456789abcdef0123456789abcdef")
claims := New()
claims.Set("name", "Billy Mister")

token, err := claims.Generate(secretKey)
if err != nil {
	panic(err)
}

parsedClaims, err := Parse(token)
if err != nil {
	panic(err)
}

fmt.Println(parsedClaims.Has("name"))
Output:

true
Example (PublicClaims)
// Add Claims
claims := New()
claims.Set("username", "billymister")
claims.Set("account_id", 8675309)

// Generate jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
jwt, err := claims.Generate(secretKey)
if err != nil {
	panic(err)
}
fmt.Println(jwt)
Example (RegisteredClaims)
// Add Claims
claims := New()
claims.SetTokenID()                                  // UUID generated
claims.SetSubject("Subject Title")                   // Subject of the token
claims.SetIssuer("Google")                           // Issuer of the token
claims.SetAudience([]string{"Google", "Facebook"})   // Audience the toke is for
claims.SetIssuedAt(time.Now())                       // IssuedAt in time, value is set in unix
claims.SetNotBeforeAt(time.Now().Add(time.Hour * 1)) // Token valid in 1 hour
claims.SetExpiresAt(time.Now().Add(time.Hour * 24))  // Token expires in 24 hours

// Generate jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
jwt, err := claims.Generate(secretKey)
if err != nil {
	panic(err)
}
fmt.Println(jwt)
Example (StructToClaims)
type Info struct {
	Name string `json:"name"`
}

// Marshal your struct into claims
info := Info{Name: "Billy Mister"}
claims, err := ToClaims(info)
if err != nil {
	panic(err)
}

// Generate jwt
secretKey := []byte("0123456789abcdef0123456789abcdef")
jwt, err := claims.Generate(secretKey)
if err != nil {
	panic(err)
}
fmt.Println(len(jwt) > 0)
Output:

true
Example (VerifySignature)
secretKey := []byte("0123456789abcdef0123456789abcdef")
claims := New()
claims.Set("name", "Billy Mister")

token, err := claims.Generate(secretKey)
if err != nil {
	panic(err)
}

verified := Verify(token, secretKey)
fmt.Println(verified)
Output:

true

Index

Examples

Constants

View Source
const (
	// TokenID is a unique identifier for this token
	TokenID = "jti"

	// Issuer is the principal that issued the token
	Issuer = "iss"

	// Audience identifies the recipents the token is intended for
	Audience = "aud"

	// Subject is the subject of the token
	Subject = "sub"

	// IssuedAt is a timesatamp for when the token was issued
	IssuedAt = "iat"

	// ExpiresAt is a timestamp for when the token should expire
	ExpiresAt = "exp"

	// NotBeforeAt is a timestamp for which this token should not be excepted until
	NotBeforeAt = "nbf"
)

Variables

View Source
var (
	// ErrNotFound is an error string clarifying
	// that the attempted key does not exist in the claims
	ErrNotFound = errors.New("claim key not found in claims")

	// ErrClaimValueInvalid is an error string clarifying
	// that the attempt to retrieve a value could not be properly converted
	ErrClaimValueInvalid = errors.New("claim value invalid")

	// ErrTokenInvalid is an error string clarifying
	// the provided token is an invalid format
	ErrTokenInvalid = errors.New("token is invalid")

	// ErrTokenHasExpired is an error string clarifying
	// the current unix timestamp has exceed the exp unix timestamp
	ErrTokenHasExpired = errors.New("token has expired")

	// ErrTokenNotYetValid is an error string clarifying
	// the current unix timestamp has not exceeded the nbf unix timestamp
	ErrTokenNotYetValid = errors.New("token is not yet valid")

	// ErrTokenSignatureInvalid clarifies the token signature did not match the expected value
	ErrTokenSignatureInvalid = errors.New("token signature invalid")

	// ErrTokenHeaderInvalid clarifies the token header is malformed or unsupported
	ErrTokenHeaderInvalid = errors.New("token header invalid")

	// ErrTokenAlgorithmMismatch clarifies that the token algorithm does not match the supported algorithm
	ErrTokenAlgorithmMismatch = errors.New("token algorithm mismatch")

	// ErrSecretTooShort clarifies that the provided secret is weaker than the minimum required length
	ErrSecretTooShort = errors.New("secret key too short; use at least 32 random bytes")
)

Functions

func ID added in v1.0.0

func ID() string

ID returns a 20 character, crypto-random identifier using a friendly alphabet.

func Verify

func Verify(tokenStr string, secret []byte) bool

Verify will take in the token string and secret and identify the signature matches

Types

type Claims

type Claims map[string]any

Claims is the main container for our body information

func New

func New() *Claims

New will initiate a new claims

func Parse added in v0.3.0

func Parse(tokenStr string) (Claims, error)

Parse takes in the token string and returns the claims payload (without verifying the signature)

func ToClaims

func ToClaims(struc any) (Claims, error)

ToClaims takes in an interface and unmarshals it to claims

func (Claims) Del

func (c Claims) Del(name string)

Del deletes a name/value from claims

func (Claims) DeleteAudience

func (c Claims) DeleteAudience()

DeleteAudience deletes audience

func (Claims) DeleteExpiresAt

func (c Claims) DeleteExpiresAt()

DeleteExpiresAt deletes expires at

func (Claims) DeleteIssuedAt

func (c Claims) DeleteIssuedAt()

DeleteIssuedAt deletes issued at

func (Claims) DeleteIssuer

func (c Claims) DeleteIssuer()

DeleteIssuer deletes issuer

func (Claims) DeleteNotBeforeAt

func (c Claims) DeleteNotBeforeAt()

DeleteNotBeforeAt deletes not before at

func (Claims) DeleteSubject

func (c Claims) DeleteSubject()

DeleteSubject deletes token id

func (Claims) DeleteTokenID

func (c Claims) DeleteTokenID()

DeleteTokenID deletes token id

func (Claims) Generate

func (c Claims) Generate(secret []byte) (string, error)

Generate takes in claims and a secret and outputs jwt token

func (Claims) Get

func (c Claims) Get(name string) (any, error)

Get gets claim value

func (Claims) GetAudience

func (c Claims) GetAudience() ([]string, error)

GetAudience will get the audience set on the Claims

func (Claims) GetBool

func (c Claims) GetBool(name string) (bool, error)

GetBool will get the boolean value on the Claims

func (Claims) GetExpiresAt

func (c Claims) GetExpiresAt() (int64, error)

GetExpiresAt will get the expires at timestamp set on the Claims

func (Claims) GetFloat

func (c Claims) GetFloat(name string) (float64, error)

GetFloat will get the float value on the Claims

func (Claims) GetInt

func (c Claims) GetInt(name string) (int, error)

GetInt will get the int value on the Claims

func (Claims) GetIssuedAt

func (c Claims) GetIssuedAt() (int64, error)

GetIssuedAt will get the issued at timestamp set on the Claims

func (Claims) GetIssuer

func (c Claims) GetIssuer() (string, error)

GetIssuer will get the issuer set on the Claims

func (Claims) GetNotBeforeAt

func (c Claims) GetNotBeforeAt() (int64, error)

GetNotBeforeAt will get the not before at timestamp set on the Claims

func (Claims) GetStr

func (c Claims) GetStr(name string) (string, error)

GetStr will get the string value on the Claims

func (Claims) GetSubject

func (c Claims) GetSubject() (string, error)

GetSubject will get the subject set on the Claims

func (Claims) GetTokenID

func (c Claims) GetTokenID() (string, error)

GetTokenID will get the id set on the Claims

func (Claims) Has

func (c Claims) Has(name string) bool

Has will let you know whether or not a claim exists

func (Claims) Set added in v0.5.0

func (c Claims) Set(name string, value any)

Set adds/sets a name/value to claims

func (Claims) SetAudience

func (c Claims) SetAudience(audience []string)

SetAudience will set a string value for the audience

func (Claims) SetExpiresAt

func (c Claims) SetExpiresAt(expiresAt time.Time)

SetExpiresAt will set an expires at timestamp in nanoseconds

func (Claims) SetIssuedAt

func (c Claims) SetIssuedAt(issuedAt time.Time)

SetIssuedAt will set an issued at timestamp in nanoseconds

func (Claims) SetIssuer

func (c Claims) SetIssuer(issuer string)

SetIssuer will set a string value for the issuer

func (Claims) SetNotBeforeAt

func (c Claims) SetNotBeforeAt(notbeforeAt time.Time)

SetNotBeforeAt will set an not before at timestamp in nanoseconds

func (Claims) SetSubject

func (c Claims) SetSubject(subject string)

SetSubject will set a subject value

func (Claims) SetTokenID

func (c Claims) SetTokenID()

SetTokenID will set a random id

func (Claims) ToStruct

func (c Claims) ToStruct(struc any) error

ToStruct takes your claims and sets value to struct

func (Claims) Validate

func (c Claims) Validate() error

Validate checks expiration and not before times

Jump to

Keyboard shortcuts

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