package main
import (
"fmt"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
var jwtkey = []byte("eryajf.net")
var str string
type Claims struct {
UserId uint
jwt.StandardClaims
}
func main() {
r := gin.Default()
r.GET("/set", setting)
r.GET("/get", getting)
r.Run(":8080")
}
func setting(ctx *gin.Context) {
expireTime := time.Now().Add(7 * 24 * time.Hour)
claims := &Claims{
UserId: 2,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
IssuedAt: time.Now().Unix(),
Issuer: "127.0.0.1",
Subject: "user token",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtkey)
if err != nil {
fmt.Println(err)
}
ctx.JSON(http.StatusOK, gin.H{
"code": 200, "token": tokenString})
}
func getting(ctx *gin.Context) {
tokenString := ctx.GetHeader("Authorization")
if tokenString == "" {
ctx.JSON(http.StatusUnauthorized, gin.H{
"code": 401, "msg": "权限不足"})
ctx.Abort()
return
}
token, claims, err := ParseToken(tokenString)
if err != nil || !token.Valid {
ctx.JSON(http.StatusUnauthorized, gin.H{
"code": 401, "msg": "权限不足"})
ctx.Abort()
return
}
ctx.JSON(http.StatusOK, gin.H{
"code": 200, "id": claims.UserId, "msg": "认证通过"})
}
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
Claims := &Claims{
}
token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (i interface{
}, err error) {
return jwtkey, nil
})
return token, Claims, err
}