jwt

package
v1.16.2 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 5 Imported by: 0

README

jwt

jwt is a library for generating and parsing token based on jwt.

encapsulated functions:

  • Support custom fields.
  • Support token refresh.
  • Support generating token pairs (refresh token and access token).

Example of use

One Token

package main

import (
    "github.com/Eric-Guo/sponge/pkg/jwt"
    "time"
)

func main() {
    uid := "123"

    // Case 1: default, signKey, signMethod(HS256), expiry time(24 hour)
    {
        // generate token
        jwtID, token, err := jwt.GenerateToken(uid)

        // validate token, get claims
        claims, err := jwt.ValidateToken(token)

        // refresh token
        //jwtID, newToken, err := jwt.RefreshToken(token)
    }

    // Case 2: custom signMethod, signKey, expiry time, fields, claims
    {
        now := time.Now()
        signMethod := jwt.HS384
        signKey := "your-secret-key"

        // generate token
        jwtID, token, err := jwt.GenerateToken(
            uid,
            jwt.WithGenerateTokenSignMethod(signMethod),
            jwt.WithGenerateTokenSignKey(signKey),
            jwt.WithGenerateTokenFields(map[string]interface{}{
                "name": "john",
                "role": "admin",
            }),
            jwt.WithGenerateTokenClaims([]jwt.RegisteredClaimsOption{
                jwt.WithExpires(time.Hour * 12),
                jwt.WithIssuedAt(now),
                // jwt.WithSubject("123"),
                // jwt.WithIssuer("https://auth.example.com"),
                // jwt.WithAudience("https://api.example.com"),
                // jwt.WithNotBefore(now),
                // jwt.WithJwtID("abc1234xxx"),
            }...),
        )

        // validate token, get claims
        claims, err := jwt.ValidateToken(token)

        // refresh token
        //jwtID, newToken, err := jwt.RefreshToken(
        //    token,
        //    jwt.WithRefreshTokenSignKey(signKey),
        //    jwt.WithRefreshTokenExpire(time.Hour*12),
        //)
    }
}

Tip: jwtID is used to prevent replay attacks. If you need to kick the user offline, you can add it to the blacklist and reject it directly next time you request it.


Two Tokens

package main

import (
    "github.com/Eric-Guo/sponge/pkg/jwt"
    "time"
)

func main() {
    uid := "123"

    // Case 1: default, signKey, signMethod(HS256), expiry time(24 hour)
    {
        // generate token
        tokens, err := jwt.GenerateTwoTokens(uid)

        // validate token, get claims
        claims, err := jwt.ValidateToken(tokens.AccessToken)

        // refresh token, get new access token, if refresh token is expired time is less than 3 hours, will refresh token too.
        //newAccessTokens, err := jwt.RefreshTwoTokens(tokens.RefreshToken, tokens.AccessToken)
    }

    // Case 2: custom signMethod, signKey, expiry time, fields, claims
    {
        now := time.Now()
        signMethod := jwt.HS384
        signKey := "your-secret-key"

        // generate token
        tokens, err := jwt.GenerateTwoTokens(
            uid,
            jwt.WithGenerateTwoTokensSignMethod(signMethod),
            jwt.WithGenerateTwoTokensSignKey(signKey),
            jwt.WithGenerateTwoTokensFields(map[string]interface{}{
                "name": "john",
                "role": "admin",
            }),
            jwt.WithGenerateTwoTokensRefreshTokenClaims([]jwt.RegisteredClaimsOption{
                jwt.WithExpires(time.Hour * 24 * 15),
                jwt.WithIssuedAt(now),
                // jwt.WithSubject("123"),
                // jwt.WithIssuer("https://auth.example.com"),
                // jwt.WithAudience("https://api.example.com"),
                // jwt.WithNotBefore(now),
                // jwt.WithJwtID("abc1234xxx"),
            }...),
            jwt.WithGenerateTwoTokensAccessTokenClaims([]jwt.RegisteredClaimsOption{
                jwt.WithExpires(time.Minute * 15),
                jwt.WithIssuedAt(now),
                // jwt.WithSubject("123"),
                // jwt.WithIssuer("https://auth.example.com"),
                // jwt.WithAudience("https://api.example.com"),
                // jwt.WithNotBefore(now),
                // jwt.WithJwtID("abc1234xxx"),
            }...),
        )

        // validate token, get claims
        claims, err := jwt.ValidateToken(tokens.AccessToken)

        // refresh token
        newTokens, err := jwt.RefreshTwoTokens(
            tokens.RefreshToken,
            tokens.AccessToken,
            jwt.WithRefreshTwoTokensSignKey(signKey),
            jwt.WithRefreshTwoTokensRefreshTokenExpires(time.Hour*24*15),
            jwt.WithRefreshTwoTokensAccessTokenExpires(time.Minute*15),
        )
    }
}

Note: If you used sponge<=v1.12.8 and referenced this library in your project code, update to the latest version and cause compilation errors, replace the batch import path github.com/Eric-Guo/sponge/pkg/jwt with github.com/Eric-Guo/sponge/pkg/jwt/old_jwt. old_jwt will remove in the future.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTokenExpired = jwt.ErrTokenExpired
)

Functions

func GenerateToken

func GenerateToken(uid string, opts ...GenerateTokenOption) (jwtID string, tokenStr string, err error)

GenerateToken create token by uid and name, use universal Claims

func RefreshToken

func RefreshToken(tokenString string, opts ...RefreshTokenOption) (jwtID string, tokenStr string, err error)

RefreshToken refresh token

Types

type Claims

type Claims struct {
	UID    string                 `json:"uid,omitempty"`    // user id
	Fields map[string]interface{} `json:"fields,omitempty"` // custom fields
	jwt.RegisteredClaims
}

Claims universal claims

func GetClaimsUnverified

func GetClaimsUnverified(tokenString string) (*Claims, error)

GetClaimsUnverified get claims from token, not verifying signature

func ValidateToken

func ValidateToken(tokenString string, opts ...ValidateTokenOption) (*Claims, error)

ValidateToken validate token, return error if token is invalid

func (*Claims) Get

func (c *Claims) Get(key string) (val interface{}, isExist bool)

Get custom field value by key, if not found, return false

func (*Claims) GetBool

func (c *Claims) GetBool(key string) (b bool, isExist bool)

GetBool custom field value by key, if not found, return false

func (*Claims) GetFloat64

func (c *Claims) GetFloat64(key string) (float64, bool)

GetFloat64 custom field value by key, if not found, return false

func (*Claims) GetInt

func (c *Claims) GetInt(key string) (int, bool)

GetInt custom field value by key, if not found, return false

func (*Claims) GetInt64

func (c *Claims) GetInt64(key string) (uint64, bool)

GetInt64 custom field value by key, if not found, return false

func (*Claims) GetString

func (c *Claims) GetString(key string) (string, bool)

GetString custom field value by key, if not found, return false

func (*Claims) NewToken

func (c *Claims) NewToken(d time.Duration, signMethod jwt.SigningMethod, signKey []byte) (string, error)

NewToken create new token with claims, duration, signing method and signing key

type GenerateTokenOption

type GenerateTokenOption func(*generateTokenOptions)

GenerateTokenOption set the jwt options.

func WithGenerateTokenClaims

func WithGenerateTokenClaims(opts ...RegisteredClaimsOption) GenerateTokenOption

WithGenerateTokenClaims set token claims value

func WithGenerateTokenFields

func WithGenerateTokenFields(fields map[string]interface{}) GenerateTokenOption

WithGenerateTokenFields set custom fields value

func WithGenerateTokenSignKey

func WithGenerateTokenSignKey(key []byte) GenerateTokenOption

WithGenerateTokenSignKey set sign key value

func WithGenerateTokenSignMethod

func WithGenerateTokenSignMethod(sm jwt.SigningMethod) GenerateTokenOption

WithGenerateTokenSignMethod set sign method value

type GenerateTwoTokensOption

type GenerateTwoTokensOption func(*generateTwoTokensOptions)

GenerateTwoTokensOption set the jwt options.

func WithGenerateTwoTokensAccessTokenClaims

func WithGenerateTwoTokensAccessTokenClaims(opts ...RegisteredClaimsOption) GenerateTwoTokensOption

WithGenerateTwoTokensAccessTokenClaims set Access token claims value

func WithGenerateTwoTokensFields

func WithGenerateTwoTokensFields(fields map[string]interface{}) GenerateTwoTokensOption

WithGenerateTwoTokensFields set custom fields value

func WithGenerateTwoTokensRefreshTokenClaims

func WithGenerateTwoTokensRefreshTokenClaims(opts ...RegisteredClaimsOption) GenerateTwoTokensOption

WithGenerateTwoTokensRefreshTokenClaims set refresh token claims value

func WithGenerateTwoTokensSignKey

func WithGenerateTwoTokensSignKey(key []byte) GenerateTwoTokensOption

WithGenerateTwoTokensSignKey set sign key value

func WithGenerateTwoTokensSignMethod

func WithGenerateTwoTokensSignMethod(sm jwt.SigningMethod) GenerateTwoTokensOption

WithGenerateTwoTokensSignMethod set sign method value

type RefreshTokenOption

type RefreshTokenOption func(*refreshTokenOptions)

RefreshTokenOption set refresh token options.

func WithRefreshTokenExpire

func WithRefreshTokenExpire(expire time.Duration) RefreshTokenOption

WithRefreshTokenExpire set expire value

func WithRefreshTokenSignKey

func WithRefreshTokenSignKey(key []byte) RefreshTokenOption

WithRefreshTokenSignKey set sign key value

type RefreshTwoTokensOption

type RefreshTwoTokensOption func(*refreshTwoTokensOptions)

RefreshTwoTokensOption set refresh token options.

func WithRefreshTwoTokensAccessTokenExpires

func WithRefreshTwoTokensAccessTokenExpires(d time.Duration) RefreshTwoTokensOption

WithRefreshTwoTokensAccessTokenExpires set access token expire value

func WithRefreshTwoTokensRefreshTokenExpires

func WithRefreshTwoTokensRefreshTokenExpires(d time.Duration) RefreshTwoTokensOption

WithRefreshTwoTokensRefreshTokenExpires set refresh token expire value

func WithRefreshTwoTokensSignKey

func WithRefreshTwoTokensSignKey(key []byte) RefreshTwoTokensOption

WithRefreshTwoTokensSignKey set sign key value

type RegisteredClaimsOption

type RegisteredClaimsOption func(*registeredClaimsOptions)

RegisteredClaimsOption set the registered claims options.

func WithAudience

func WithAudience(audience ...string) RegisteredClaimsOption

WithAudience set audience (aud) value

func WithDeadline

func WithDeadline(expiresAt time.Time) RegisteredClaimsOption

WithDeadline set expires (exp) value

func WithExpires

func WithExpires(d time.Duration) RegisteredClaimsOption

WithExpires set expires (exp) value

func WithIssuedAt

func WithIssuedAt(issuedAt time.Time) RegisteredClaimsOption

WithIssuedAt set issued at (iat) value

func WithIssuer

func WithIssuer(issuer string) RegisteredClaimsOption

WithIssuer set issuer (iss) value

func WithJwtID

func WithJwtID(id string) RegisteredClaimsOption

WithJwtID set jwt id (jti) value

func WithNotBefore

func WithNotBefore(notBefore time.Time) RegisteredClaimsOption

WithNotBefore set not before (nbf) value

func WithSubject

func WithSubject(subject string) RegisteredClaimsOption

WithSubject set subject (sub) value

type SigningMethodHMAC

type SigningMethodHMAC = jwt.SigningMethodHMAC

type Tokens

type Tokens struct {
	RefreshToken string `json:"refreshToken"`
	AccessToken  string `json:"accessToken"`
	JwtID        string `json:"jwtID"` // used to prevent replay attacks, identifying specific tokens
}

func GenerateTwoTokens

func GenerateTwoTokens(uid string, opts ...GenerateTwoTokensOption) (*Tokens, error)

GenerateTwoTokens create accessToken and refreshToken

func RefreshTwoTokens

func RefreshTwoTokens(refreshToken string, accessToken string, opts ...RefreshTwoTokensOption) (*Tokens, error)

RefreshTwoTokens refresh access token, if refresh token is expired time is less than 3 hours, will auto refresh token too. if return err is ErrTokenExpired, you need to login again to get token.

type ValidateTokenOption

type ValidateTokenOption func(*validateTokenOptions)

ValidateTokenOption set parse token options.

func WithValidateTokenSignKey

func WithValidateTokenSignKey(key []byte) ValidateTokenOption

WithValidateTokenSignKey set sign key value

Directories

Path Synopsis
Package jwt is deprecated, old package path is "github.com/Eric-Guo/sponge/pkg/jwt/old_jwt" Please use new jwt package instead, new package path is "github.com/Eric-Guo/sponge/pkg/jwt"
Package jwt is deprecated, old package path is "github.com/Eric-Guo/sponge/pkg/jwt/old_jwt" Please use new jwt package instead, new package path is "github.com/Eric-Guo/sponge/pkg/jwt"

Jump to

Keyboard shortcuts

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