jwt

package
v1.14.2 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2025 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/go-dev-frame/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/go-dev-frame/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/go-dev-frame/sponge/pkg/jwt with github.com/go-dev-frame/sponge/pkg/jwt/old_jwt. old_jwt will remove in the future.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	HS256 = jwt.SigningMethodHS256
	HS384 = jwt.SigningMethodHS384
	HS512 = jwt.SigningMethodHS512
)
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 added in v1.13.0

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

GetClaimsUnverified get claims from token, not verifying signature

func ValidateToken added in v1.13.0

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

ValidateToken validate token, return error if token is invalid

func (*Claims) Get added in v1.13.0

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

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

func (*Claims) GetBool added in v1.13.0

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

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

func (*Claims) GetFloat64 added in v1.13.0

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

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

func (*Claims) GetInt added in v1.13.0

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

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

func (*Claims) GetInt64 added in v1.13.0

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

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

func (*Claims) GetString added in v1.13.0

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

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

func (*Claims) NewToken added in v1.13.0

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 added in v1.13.0

type GenerateTokenOption func(*generateTokenOptions)

GenerateTokenOption set the jwt options.

func WithGenerateTokenClaims added in v1.13.0

func WithGenerateTokenClaims(opts ...RegisteredClaimsOption) GenerateTokenOption

WithGenerateTokenClaims set token claims value

func WithGenerateTokenFields added in v1.13.0

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

WithGenerateTokenFields set custom fields value

func WithGenerateTokenSignKey added in v1.13.0

func WithGenerateTokenSignKey(key []byte) GenerateTokenOption

WithGenerateTokenSignKey set sign key value

func WithGenerateTokenSignMethod added in v1.13.0

func WithGenerateTokenSignMethod(sm jwt.SigningMethod) GenerateTokenOption

WithGenerateTokenSignMethod set sign method value

type GenerateTwoTokensOption added in v1.13.0

type GenerateTwoTokensOption func(*generateTwoTokensOptions)

GenerateTwoTokensOption set the jwt options.

func WithGenerateTwoTokensAccessTokenClaims added in v1.13.0

func WithGenerateTwoTokensAccessTokenClaims(opts ...RegisteredClaimsOption) GenerateTwoTokensOption

WithGenerateTwoTokensAccessTokenClaims set Access token claims value

func WithGenerateTwoTokensFields added in v1.13.0

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

WithGenerateTwoTokensFields set custom fields value

func WithGenerateTwoTokensRefreshTokenClaims added in v1.13.0

func WithGenerateTwoTokensRefreshTokenClaims(opts ...RegisteredClaimsOption) GenerateTwoTokensOption

WithGenerateTwoTokensRefreshTokenClaims set refresh token claims value

func WithGenerateTwoTokensSignKey added in v1.13.0

func WithGenerateTwoTokensSignKey(key []byte) GenerateTwoTokensOption

WithGenerateTwoTokensSignKey set sign key value

func WithGenerateTwoTokensSignMethod added in v1.13.0

func WithGenerateTwoTokensSignMethod(sm jwt.SigningMethod) GenerateTwoTokensOption

WithGenerateTwoTokensSignMethod set sign method value

type RefreshTokenOption added in v1.13.0

type RefreshTokenOption func(*refreshTokenOptions)

RefreshTokenOption set refresh token options.

func WithRefreshTokenExpire added in v1.13.0

func WithRefreshTokenExpire(expire time.Duration) RefreshTokenOption

WithRefreshTokenExpire set expire value

func WithRefreshTokenSignKey added in v1.13.0

func WithRefreshTokenSignKey(key []byte) RefreshTokenOption

WithRefreshTokenSignKey set sign key value

type RefreshTwoTokensOption added in v1.13.0

type RefreshTwoTokensOption func(*refreshTwoTokensOptions)

RefreshTwoTokensOption set refresh token options.

func WithRefreshTwoTokensAccessTokenExpires added in v1.13.0

func WithRefreshTwoTokensAccessTokenExpires(d time.Duration) RefreshTwoTokensOption

WithRefreshTwoTokensAccessTokenExpires set access token expire value

func WithRefreshTwoTokensRefreshTokenExpires added in v1.13.0

func WithRefreshTwoTokensRefreshTokenExpires(d time.Duration) RefreshTwoTokensOption

WithRefreshTwoTokensRefreshTokenExpires set refresh token expire value

func WithRefreshTwoTokensSignKey added in v1.13.0

func WithRefreshTwoTokensSignKey(key []byte) RefreshTwoTokensOption

WithRefreshTwoTokensSignKey set sign key value

type RegisteredClaimsOption added in v1.13.0

type RegisteredClaimsOption func(*registeredClaimsOptions)

RegisteredClaimsOption set the registered claims options.

func WithAudience added in v1.13.0

func WithAudience(audience ...string) RegisteredClaimsOption

WithAudience set audience (aud) value

func WithDeadline added in v1.13.0

func WithDeadline(expiresAt time.Time) RegisteredClaimsOption

WithDeadline set expires (exp) value

func WithExpires added in v1.13.0

func WithExpires(d time.Duration) RegisteredClaimsOption

WithExpires set expires (exp) value

func WithIssuedAt added in v1.13.0

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 added in v1.13.0

func WithJwtID(id string) RegisteredClaimsOption

WithJwtID set jwt id (jti) value

func WithNotBefore added in v1.13.0

func WithNotBefore(notBefore time.Time) RegisteredClaimsOption

WithNotBefore set not before (nbf) value

func WithSubject added in v1.13.0

func WithSubject(subject string) RegisteredClaimsOption

WithSubject set subject (sub) value

type SigningMethodHMAC added in v1.13.2

type SigningMethodHMAC = jwt.SigningMethodHMAC

type Tokens added in v1.13.0

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 added in v1.13.0

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

GenerateTwoTokens create accessToken and refreshToken

func RefreshTwoTokens added in v1.13.0

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 added in v1.13.0

type ValidateTokenOption func(*validateTokenOptions)

ValidateTokenOption set parse token options.

func WithValidateTokenSignKey added in v1.13.0

func WithValidateTokenSignKey(key []byte) ValidateTokenOption

WithValidateTokenSignKey set sign key value

Directories

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

Jump to

Keyboard shortcuts

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