添加jwt 生成token

master
ZGGSONG 3 years ago
parent 7d70ba4236
commit 4af62b27cb

@ -0,0 +1,36 @@
package common
import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/zggsong/gin-vue-demo/model"
)
var jwtKey = []byte("a_secret_key")
type Claims struct {
UserId uint
jwt.StandardClaims
}
func ReleaseToken(user model.User) (string, error) {
// 设置Token过期时间
expirationTime := time.Now().Add(7 * 24 * time.Hour)
claims := Claims{
UserId: user.ID,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
IssuedAt: time.Now().Unix(),
Issuer: "github.com/zggsong/gin-vue-demo",
Subject: "user token",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", err
}
return tokenString, nil
}

@ -52,7 +52,14 @@ func Login(ctx *gin.Context) {
}
// 发放Token
token := "111"
token, err := common.ReleaseToken(user)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"code": http.StatusInternalServerError,
"message": "发放Token失败",
})
return
}
// 返回结果
ctx.JSON(200, gin.H{

@ -9,6 +9,7 @@ require (
)
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect

@ -1,6 +1,8 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs=

Loading…
Cancel
Save