zdpgo_jwt

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2022 License: MIT Imports: 2 Imported by: 1

README

zdpgo_jwt

使用Golang创建、刷新和校验JWT Token

项目地址:https://github.com/zhangdapeng520/zdpgo_jwt

功能清单

  • 创建token
  • 校验token
  • 刷新token

版本历史

  • 版本0.1.0 2022年3月9日 基本功能
  • 版本0.1.1 2022年4月4日 代码优化

使用示例

创建、校验和刷新token
package main

import (
	"fmt"
	"github.com/zhangdapeng520/zdpgo_jwt"
	"github.com/zhangdapeng520/zdpgo_jwt/core/config"
	"github.com/zhangdapeng520/zdpgo_jwt/libs/jwtgo"
	"time"
)

func main() {
	j := zdpgo_jwt.New(config.Config{})

	// 1、创建token
	data := map[string]interface{}{
		"a": 111,
		"b": 2.222,
		"c": true,
	}

	maxAge := 60 * 60 * 24
	token, err := j.CreateToken(config.Claims{
		UserId:   1,
		Username: "zhangdapeng",
		UserType: "username",
		Role:     1,
		Data:     data,
		StandardClaims: jwtgo.StandardClaims{
			ExpiresAt: time.Now().Add(time.Duration(maxAge) * time.Second).Unix(), // 过期时间,必须设置
		},
	})
	if err != nil {
		fmt.Println("创建token失败:", err)
		return
	}
	fmt.Println("得到token内容:", token)

	// 2、验证token
	claims, err := j.ParseToken(token)
	if err != nil {
		fmt.Println("解析token失败:", err)
		return
	}
	fmt.Println("得到token内容:", claims)

	// 3、刷新token
	tokenNew, err := j.RefreshToken(token)
	if err != nil {
		fmt.Println("更新token失败:", tokenNew)
		return
	}

	// 4、校验旧的token和新的token
	claims1, err := j.ParseToken(token)
	if err != nil {
		fmt.Println("解析token失败:", err)
		return
	}
	fmt.Println("得到旧token内容:", claims1)

	claims2, err := j.ParseToken(token)
	if err != nil {
		fmt.Println("解析token失败:", err)
		return
	}
	fmt.Println("得到刷新token内容:", claims2)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Generate

type Generate interface {
	// CreateToken 创建TOKEN
	CreateToken(claims config.Claims) (string, error)
}

type Jwt

type Jwt struct {
	// 方法区
	CreateToken  func(claims config.Claims) (string, error)
	ParseToken   func(tokenString string) (*config.Claims, error)
	RefreshToken func(tokenString string) (string, error)
}

Jwt Jwt核心对象

func New

func New(cfg config.Config) *Jwt

New 创建Jwt对象

type Parse

type Parse interface {
	// ParseToken 解析TOKEN
	ParseToken(tokenString string) (*config.Claims, error)
}

type Refresh

type Refresh interface {
	// RefreshToken 刷新TOKEN
	RefreshToken(tokenString string) (string, error)
}

type Token

type Token interface {
	Generate
	Parse
	Refresh
}

Token TOKEN接口

Directories

Path Synopsis
core
jwt
examples
z01_hello command
libs
jwtgo/cmd/jwt command
A useful example app.
A useful example app.

Jump to

Keyboard shortcuts

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