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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| package middleware
import ( "encoding/json" "gin_project/config" "gin_project/model" "log" "net/http" "strconv" "strings"
"github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" )
type CustomClaims struct { User string `json:"user"` jwt.StandardClaims }
func Auth() gin.HandlerFunc { return func(context *gin.Context) {
result := model.Result{ Code: http.StatusUnauthorized, Message: "无法认证,重新登录", Data: nil, } auth := context.Request.Header.Get("Authorization")
if len(auth) == 0 { context.Abort() context.JSON(http.StatusUnauthorized, result) return }
auth = strings.Fields(auth)[1] claims, err := parseToken(auth) if err != nil { result.Message = "token error " + err.Error() context.AbortWithStatusJSON(http.StatusUnauthorized, result) } else { println("token 正确") } context.Set("claims", claims)
context.Next() } }
func parseToken(token string) (*CustomClaims, error) { payload := strings.Split(token, ".") bytes, e := jwt.DecodeSegment(payload[1])
if e != nil { println(e.Error()) } var cm CustomClaims if err := json.Unmarshal(bytes, &cm); err != nil { log.Println(err) } i := cm.Id ID, err := strconv.Atoi(i) if err != nil { println(err.Error()) } user := model.User{} user.ID = uint(ID) u := model.User.QueryByID(user) jwtToken, err := jwt.ParseWithClaims(token, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) { return []byte(config.Secret + u.PasswordDigest), nil }) if err == nil && jwtToken != nil { if claim, ok := jwtToken.Claims.(*CustomClaims); ok && jwtToken.Valid { return claim, nil } } return nil, err }
|