Go language integrates jwt+gin framework to realize token

download library

go get -u  github.com/dgrijalva/jwt-go

Write jwt related methods (generate token and parse token)


import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"log"
	"time"
)

// jwt身份验证demo

// 设置jwt密钥secret
var jwtSecret = []byte("123")

type Claims struct {
    
    
	UserID int `json:"userId"`
	jwt.StandardClaims
}

const expire_time = 30 * time.Minute

// GenerateToken 生成token的函数
func GenerateToken(userId int) (string, error) {
    
    
	nowTime := time.Now()
	expireTime := nowTime.Add(expire_time)

	claims := Claims{
    
    
		userId, // 自行添加的信息
		jwt.StandardClaims{
    
    
			ExpiresAt: expireTime.Unix(), // 设置token过期时间
			Issuer:    "admin",           // 设置jwt签发者
		},
	}
	// 生成token
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

// ParseToken 验证token的函数
func ParseToken(token string) (*Claims, error) {
    
    
	// 对token的密钥进行验证
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{
    
    }, func(token *jwt.Token) (interface{
    
    }, error) {
    
    
		return jwtSecret, nil
	})

	// 判断token是否过期
	if tokenClaims != nil {
    
    
		claims, _ := tokenClaims.Claims.(*Claims)
		return claims, nil
	}
	return nil, err
}

Write jwt middleware

The purpose of writing middleware

In order to verify the token first when accessing the interface, if the token verification fails, there is no need to go through the follow-up logic.

jwt middleware code


import (
	"github.com/gin-gonic/gin"
	"medicalRecrypt/common/jwtConfig"
	"net/http"
	"time"
)

func JWT() gin.HandlerFunc {
    
    
	return func(context *gin.Context) {
    
    
		// 获取token
		token := context.GetHeader("Token")

		if token == "" {
    
    
			context.JSON(http.StatusOK, gin.H{
    
    
				"code": http.StatusUnauthorized,
				"msg":  "没有携带token",
				"data": "",
			})
			context.Abort()
			return
		} else {
    
    
			claims, err := jwtConfig.ParseToken(token)
			if err != nil {
    
    
				context.JSON(http.StatusOK, gin.H{
    
    
					"code": http.StatusUnauthorized,
					"msg":  "token验证失败",
					"data": "",
				})
				context.Abort()
				return
			} else if time.Now().Unix() > claims.StandardClaims.ExpiresAt {
    
    
				context.JSON(http.StatusOK, gin.H{
    
    
					"code": http.StatusUnauthorized,
					"msg":  "token已过期",
					"data": "",
				})
				context.Abort()
				return
			}
		}
	}
}

Register routing through gin to achieve http access


import (
	"fmt"
	"github.com/gin-gonic/gin"
	"medicalRecrypt/controller"
)

func main() {
    
    

	//创建路由
	r := gin.Default()
	//注册组和中间件
	v1 := r.Group("/user")
	{
    
    
		//限制文件大小,默认32M,限制为1M
		r.MaxMultipartMemory = 1 << 20
		v1.POST("/login", controller.Login)
	}
	//使用jwt中间件
	v2 := r.Group("/file").Use(controller.JWT())
	{
    
    

		v2.POST("/downloadpem", controller.DownloadFile)

	}
	r.Run(":8888")
}

Test Results

insert image description here

Access with token

insert image description here

expired token

insert image description here

Guess you like

Origin blog.csdn.net/ydl1128/article/details/127704439