diff --git a/common/jwt.go b/common/jwt.go new file mode 100644 index 0000000..5685c62 --- /dev/null +++ b/common/jwt.go @@ -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 +} diff --git a/controller/login.go b/controller/login.go index 2229f13..afa8150 100644 --- a/controller/login.go +++ b/controller/login.go @@ -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{ diff --git a/go.mod b/go.mod index a9fdb7b..dfda02d 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index 362280a..3a5c147 100644 --- a/go.sum +++ b/go.sum @@ -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=