gin jwt鉴权

GoLang gin gorm 学习笔记

jwt鉴权

引入库

import (
	"github.com/dgrijalva/jwt-go"
)

创建jwt并加密返回token

type MyClaims struct {
	jwt.StandardClaims
	Name string `json:"name"`
}

func main() {
    secret :="liujunjie"
    // token数据
	c := MyClaims{
		Name: "liujunjie",
		StandardClaims: jwt.StandardClaims{
			NotBefore: int64(time.Now().Unix() - 1000),
			ExpiresAt: 15000,
			Issuer:    "liujunjie",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
    // 加密
    tokenString, err := token.SignedString([]byte(secret))
}

解密 token

tokenText,e := jwt.ParseWithClaims(tokenString, &c, func(token *jwt.Token) (interface{}, error) {
    return []byte(secret), nil
})
if e!=nil{
    fmt.Println(err)
}
fmt.Println(tokenText.Claims.(*MyClaims).Name)