github
Documentation
引入包
1
| go get "github.com/dgrijalva/jwt-go"
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| package common
import ( "gin_vue_bs/model" "time"
"github.com/dgrijalva/jwt-go" )
//定义 jwt 加密密钥 var jwtKey = []byte("a_secret_crect")
//Claims . type Claims struct { UserID uint jwt.StandardClaims }
//ReleaseToken 登录成功则调用该方法发放token. func ReleaseToken(user model.User) (string, error) { expirationTime := time.Now().Add(7 * 24 * time.Hour) //token的过期时间7天 claims := &Claims{ UserID: user.ID, StandardClaims: jwt.StandardClaims{ ExpiresAt: expirationTime.Unix(), IssuedAt: time.Now().Unix(), //token发放时间 Issuer: "samtake", //是谁发放的token Subject: "user token", //主题 }, }
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenString, err := token.SignedString(jwtKey)
if err != nil { return "", err }
return tokenString, nil }
|
返回
1 2 3 4 5 6 7
| { "code": "200", "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOjMsImV4cCI6MTU4NzA1MjA0MiwiaWF0IjoxNTg2NDQ3MjQyLCJpc3MiOiJzYW10YWtlIiwic3ViIjoidXNlciB0b2tlbiJ9.6a50w6SfsQH7XZBW7zu3_FEGFcrWHRAh2DFYTh9hbCo" }, "msg": "登录成功" }
|
所返回的token由三部分组成:协议头(token的加密协议)、 源码claims储存的信息 、(前面两部分+jwtKey)的哈希值:
1 2 3 4 5 6 7
| ➜ blogs echo eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 | base64 -D {"alg":"HS256","typ":"JWT"}% ➜ blogs echo eyJVc2VySUQiOjMsImV4cCI6MTU4NzA1MjA0MiwiaWF0IjoxNTg2NDQ3MjQyLCJpc3MiOiJzYW10YWtlIiwic3ViIjoidXNlciB0b2tlbiJ9 | base64 -D {"UserID":3,"exp":1587052042,"iat":1586447242,"iss":"samtake","sub":"user token"}% ➜ blogs echo 6a50w6SfsQH7XZBW7zu3_FEGFcrWHRAh2DFYTh9hbCo | base64 -D ?tä???]?V?;??Q??!?1XNa% ➜ blogs
|