package auth import ( "encoding/json" "errors" "github.com/golang-jwt/jwt" "net/http" "time" ) type UserInfo struct { UserId int64 `json:"user_id"` } // 签名key var signKey = "FushenFGbhgfhgKgGH556HGlXrsfJKhhjYFGKLO==" var expireTime = int64(3600) // 生成token func GenJwtToken(userInfo UserInfo) (token string, err error) { t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "user_id": userInfo.UserId, "exp": time.Now().Add(time.Second * time.Duration(expireTime)).Unix(), //过期时间 "iss": "fusen", }) token, err = t.SignedString([]byte(signKey)) if err != nil { return "", err } return } // 解释token func ParseJwtToken(token string) (UserInfo, error) { t, err := jwt.ParseWithClaims(token, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(signKey), nil }) if err != nil { return UserInfo{}, err } d, err := json.Marshal(t.Claims) if err != nil { return UserInfo{}, err } var userInfo UserInfo if err = json.Unmarshal(d, &userInfo); err != nil { return UserInfo{}, err } return userInfo, nil } // 检测授权 func CheckAuth(r *http.Request) (UserInfo, error) { token := r.Header.Get("Authorization") if token == "" { return UserInfo{}, errors.New("token is required") } //解析token userInfo, err := ParseJwtToken(token) if err != nil { return UserInfo{}, err } return userInfo, nil }