jwt

package
Version: v2.13.1 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2021 License: LGPL-3.0 Imports: 7 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrParseClaimsFailed = errors.New("failed to parse not standard claims")
	ErrNoPublicKey       = errors.New("no public key to verify JWT")
	ErrEmptyToken        = errors.New("token is empty")
)
View Source
var (
	ErrInvalidPrivateKeyFile = errors.New("invalid private key file")
)

Functions

func CreateClaims

func CreateClaims(issuer string, inr time.Duration) jwt.Claims

CreateClaims 根据 issuer 与过期时间间隔创建一个 JWT Claims. 例如, issuer 可以是一个 APP ID.

func HMACVerifyCustomJWT added in v2.12.0

func HMACVerifyCustomJWT(tokenString string, opt HMACVerifyOption, claims Claims) (bool, error)

HMACVerifyCustomJWT 使用 HMAC 算法 (HS256, HS384, HS512) 对包含自定义 Claims 的 JWT Token 进行验证.

Example
package main

import (
	"fmt"
	"time"

	"github.com/jinmukeji/plat-pkg/v2/auth/jwt"
)

func main() {
	// MyClaims is a custom claims
	type MyClaims struct {
		jwt.StandardClaims

		AccessToken string `json:"access_token"`
	}

	claims := &MyClaims{}

	m := make(map[string][]byte)
	m["a"] = []byte("BQysRAXxfa4MjD5ta6p51AULAdQc1bGHJJVWsRRNQCTvqZpztWm3sJErB7MgZYYeqQkdkxpT0xyjhXDoySZdraq7OHcqksQCccIHtDHqu0ujrug4qI78EGgPeeZASpKqxnVibqDLqvpnFrb8BTrIfRz8VXe4Ncv4DIZLyqUMoILflIJvabtfuv1i51km4BIPIDR6Vvw5pratnEqcLgNQipd25fHooEZtj1X70oF3A0uVFggnmljk6XEbSL3ZbEIs")
	opt := jwt.HMACVerifyOption{
		MaxExpInterval: 10 * time.Minute,
		SecretKeys:     m,
	}

	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjb20uamlubXVoZWFsdGguaGprIiwiZXhwIjoxNjIyNDQ0MjkxLCJzdWIiOiJoamsiLCJpYXQiOjE2MjI0NDM5OTEsImFjY2Vzc190b2tlbiI6IjJhYzc4ZGFjLTY4YTMtNDZjYi1iNzYxLWZmMjFmMjEwMGI3MSJ9.4A26iyNXPAZWemIs5P68Z2dOSciAh7IkqX8ldsLyQas"
	ok, err := jwt.HMACVerifyCustomJWT(token, opt, claims)
	if err != nil {
		panic(err)
	}
	fmt.Println(ok)
	fmt.Println(claims)
}
Output:

func LoadRSAPrivateKey

func LoadRSAPrivateKey(key []byte) (*rsa.PrivateKey, error)

LoadRSAPrivateKey 从私钥的字节序列中加载 RSA 私钥

func LoadRSAPrivateKeyFromPEM

func LoadRSAPrivateKeyFromPEM(keyFile, passFile string) (*rsa.PrivateKey, error)

LoadRSAPrivateKeyFromPEM 从PEM私钥文件 keyFile 与密码文件 passFile 中加载 RSA 私钥

func LoadRSAPublicKey

func LoadRSAPublicKey(key []byte) (*rsa.PublicKey, error)

LoadRSAPublicKey 从字节序列中加载 RSA 公钥

func LoadRSAPublicKeyFromPEM

func LoadRSAPublicKeyFromPEM(file string) (*rsa.PublicKey, error)

LoadRSAPublicKeyFromPEM 从PEM公钥文件 file 中加载 RSA 公钥

func RS256SignJWT

func RS256SignJWT(claims jwt.Claims, key *rsa.PrivateKey) (string, error)

RS256SignJWT 使用 RS256 算法对 claims 进行签名

func RS384SignJWT

func RS384SignJWT(claims jwt.Claims, key *rsa.PrivateKey) (string, error)

RS384SignJWT 使用 RS84 算法对 claims 进行签名

func RS512SignJWT

func RS512SignJWT(claims jwt.Claims, key *rsa.PrivateKey) (string, error)

RS512SignJWT 使用 RS512 算法对 claims 进行签名

func RSAVerifyCustomJWT

func RSAVerifyCustomJWT(tokenString string, opt VerifyOption, claims Claims) (bool, error)

RSAVerifyCustomJWT 使用 RSA 算法(RS256/RS384/RS512) 对包含自定义 Claims 的 JWT Token 进行验证.

Example
package main

import (
	"crypto/rsa"
	"fmt"
	"time"

	"github.com/jinmukeji/plat-pkg/v2/auth/jwt"
)

func main() {
	// MyClaims is a custom claims
	type MyClaims struct {
		jwt.StandardClaims

		AccessToken string `json:"access_token"`
	}

	token := "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTQwNTMyMTQsImlhdCI6MTU5NDA1MjYxNCwiaXNzIjoiYXBwLXRlc3QxIn0.Xj2bALCrcIMHLHmeeI7ipRddoxU21MmigH3EBr9T_wygkZiZyzOOs-KU2VKuwMhnVsI0vU1iQKs0lCoHt8hSUGddHBjQ4oXcgfo9LWeKl0mluAeVzuBVsI-cZqDAapn5vKRrHvw2IsF-luJNB9th9-HY3_4Nif7OOKGc7DoYkzy-gazKl1lqOH76cy9jQBZ_FNYyKKh28_FgBECxoOogAfakyclPLfXjIxqvpAMMYYp3x0Gbeb1NtRToLNEHeJBEAs1W3vgCQ9i3DF2F1PP3XKHWifUp6MANMgt3w1ghPxxUK2MRHe1oX6wnu652GtspKQ0EJq5GnWMTie0KdRZCfw"
	key, err := jwt.LoadRSAPublicKeyFromPEM("public_key.pem")
	if err != nil {
		panic(err)
	}

	opt := jwt.VerifyOption{
		MaxExpInterval: 10 * time.Minute,
		GetPublicKeyFunc: func(iss string) *rsa.PublicKey {
			// ignore iss check

			return key
		},
	}

	claims := MyClaims{}

	valid, err := jwt.RSAVerifyCustomJWT(token, opt, &claims)
	fmt.Printf("IsValid: %v\n", valid)
	if err != nil {
		fmt.Printf("Validation Error: %v\n", err)
	}
	fmt.Println("Claims:", claims)
}
Output:

func RSAVerifyJWT

func RSAVerifyJWT(tokenString string, opt VerifyOption) (bool, *jwt.StandardClaims, error)

RSAVerifyJWT 使用 RSA 算法(RS256/RS384/RS512) 对 JWT Token 进行验证.

func RSAVerifyJWTWithKid added in v2.13.0

func RSAVerifyJWTWithKid(tokenString string, opt KidVerifyOption) (bool, *jwt.StandardClaims, error)

RSAVerifyJWTWithKid 使用 RSA 算法(RS256/RS384/RS512) 对 JWT Token 进行验证.

Example
package main

import (
	"crypto/rsa"
	"fmt"
	"time"

	"github.com/jinmukeji/plat-pkg/v2/auth/jwt"
)

func main() {

	token := "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImhteSJ9.eyJpc3MiOiJjb20uamlubXVoZWFsdGguaG15IiwiZXhwIjoxNjI0OTM2NDIwLCJzdWIiOiJobXkiLCJpYXQiOjE2MjQ5MzYxMjB9.rSEgdLncgTtec19dV7VDo0tr_nTbfXl2qVqW96ezRR7aM5MPHuppSVCs-bgFkBiEEXGqKPNxOYprEKlSmAXwQGhQ7HGc6vdCe1GE0GqK0j0Bs_kihicmUCAP9AZU-hoqN98wm4wBO-z51Tc1Sio8ZTRig7ICp3OvlCvA9ZkFg694WuCSJNBIG-8JEUzJxNY1kaXwlxN7jQLW_zyNrFAeIyOSTCeITgL9a7VOA85l0VB36mjBY30uZNyOmUOnAurukfYkQxlEpU9d0E0vVcvtcpszU-ahT53WoNHmSWhdfcTkU9eGUucV0RNUQKVHdkqU75gx5diCO5F8mQIfzAJ_Eg"
	key, err := jwt.LoadRSAPublicKeyFromPEM("./a.pem")
	if err != nil {
		panic(err)
	}

	opt := jwt.KidVerifyOption{
		MaxExpInterval: 10 * time.Minute,
		GetPublicKeyFunc: func(iss string) *rsa.PublicKey {
			// ignore iss check

			return key
		},
	}

	valid, claims, err := jwt.RSAVerifyJWTWithKid(token, opt)
	fmt.Printf("IsValid: %v\n", valid)
	if err != nil {
		fmt.Printf("Validation Error: %v\n", err)
	}
	fmt.Println("Claims:", claims)
}
Output:

Types

type Claims

type Claims interface {
	jwt.Claims

	// GetIssuer 返回 iss
	GetIssuer() string
	// GetExpiresAt 返回 exp
	GetExpiresAt() int64
	// GetIssuedAt 返回 iat
	GetIssuedAt() int64
}

type GetPublicKeyByKidFunc added in v2.13.0

type GetPublicKeyByKidFunc func(kid string) *rsa.PublicKey

GetPublicKeyByKidFunc 根据 kid 获取一个 rsa.PublicKey

type GetPublicKeyFunc

type GetPublicKeyFunc func(iss string) *rsa.PublicKey

GetPublicKeyFunc 根据 iss 获取一个 rsa.PublicKey

type HMACVerifyOption added in v2.12.0

type HMACVerifyOption struct {
	MaxExpInterval time.Duration // 最大过期时间间隔,单位为秒.
	// app-key与密钥的对应关系
	// key: app-key
	// value : 密钥的byte数组
	SecretKeys map[string][]byte
}

HMACVerifyOption 验证参数

type KidVerifyOption added in v2.13.0

type KidVerifyOption struct {
	MaxExpInterval   time.Duration         // 最大过期时间间隔,单位为秒.
	GetPublicKeyFunc GetPublicKeyByKidFunc // PublicKey 查找函数
}

KidVerifyOption 验证参数

type StandardClaims

type StandardClaims struct {
	jwt.StandardClaims
}

StandardClaims is a wrapper for jwt.StandardClaims.

func (*StandardClaims) GetExpiresAt

func (c *StandardClaims) GetExpiresAt() int64

func (*StandardClaims) GetIssuedAt

func (c *StandardClaims) GetIssuedAt() int64

func (*StandardClaims) GetIssuer

func (c *StandardClaims) GetIssuer() string

type VerifyOption

type VerifyOption struct {
	MaxExpInterval   time.Duration    // 最大过期时间间隔,单位为秒.
	GetPublicKeyFunc GetPublicKeyFunc // PublicKey 查找函数
}

VerifyOption 验证参数

Directories

Path Synopsis
tools

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL