jwt-go token

使用第三方库:github.com/dgrijalva/jwt-go

直接上代码:

package main

import (
    "errors"
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "strings"
    "time"
    "github.com/gin-gonic/gin"
)


// model
type User struct {
    Id          uint     `json:"id"`
    Username    string   `json:"username" sql:"type:varchar(255), notnull, unique" binding:"required"`
    Password    string   `json:"-" sql:"type:varchar(255), notnull" binding:"required"`
    FullName    string   `json:"full_name" sql:"type:varchar(255)"`
    Permissions []string `json:"permissions"`
}

var (
    Secret = "test_secret" // 加盐
    ExpireTime = 3600  // token有效期
    StrToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NDI5NzAyMDMsImlhdCI6MTU0Mjk2NjYwMywidXNlcl9pZCI6MSwidXNlcm5hbWUiOiLlvKDkuIkiLCJmdWxsX25hbWUiOiLlvKDkuIkiLCJwZXJtaXNzaW9ucyI6W119.51RTsbpCmdcW6KRaEXa46-U6cWbs3OOEoiC2vUNzQ3w"
)

type JWTClaims struct {  // token里面添加用户信息,验证token后可能会用到用户信息
    jwt.StandardClaims
    UserID      uint     `json:"user_id"`
    Username    string   `json:"username"`
    FullName    string   `json:"full_name"`
    Permissions []string `json:"permissions"`
}

func (c *JWTClaims) SetExpiredAt(expiredAt int64) {
    c.ExpiresAt = expiredAt
}


func main() {
    tokenObtain()
    tokenRefresh()
    tokenVerify()
}

// 生成token
func tokenObtain() {
    user := User{
        Id:1,
        Username:"张三",
        FullName:"张三",
        Permissions:[]string{},
    }
    claims := JWTClaims{
        UserID:      user.Id,
        Username:    user.Username,
        FullName:    user.FullName,
        Permissions: user.Permissions,
    }
    claims.IssuedAt = time.Now().Unix()
    claims.SetExpiredAt(time.Now().Add(time.Second * time.Duration(ExpireTime)).Unix())

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    signedToken, err := token.SignedString([]byte(Secret))
    if err != nil {
        println(err)
        return
    }
    fmt.Println(signedToken)
}

// =======================

// 刷新token
func tokenRefresh()  {
    token, err := jwt.ParseWithClaims(StrToken, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(Secret), nil
    })
    if err != nil {
        println(err)
        return
    }
    claims, ok := token.Claims.(*JWTClaims)
    if !ok {
        println("test")
        return
    }
    if err := token.Claims.Valid(); err != nil {
        println(err)
        return
    }
    user := User{
        Id:1,
        Username:"张三",
        FullName:"张三",
        Permissions:[]string{},
    }
    claims.FullName = user.FullName
    claims.Username = user.Username
    claims.Permissions = user.Permissions
    claims.ExpiresAt = time.Now().Unix() + (claims.ExpiresAt - claims.IssuedAt)

    newToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    signedToken, err := newToken.SignedString([]byte(Secret))
    if err != nil {
        println(err)
        return
    }
    fmt.Println(signedToken)
}

// =====================

// 验证token是否有效
func tokenVerify() {
    token, err := jwt.ParseWithClaims(StrToken, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(Secret), nil
    })
    if err != nil {
        println(err)
        return
    }
    if err := token.Claims.Valid(); err != nil {
        print(err)
        return
    }
    fmt.Println("ok")
}

 

token验证解析中间件:

// 路由中间件

func jwtAuthenticateMiddleware(ctx *gin.Context) {
    jwtObj := ctx.GetHeader("Authorization")
    if jwtObj == "" {
        ctx.AbortWithError(401, errors.New("Auth error, not find Autorization or Autorization is null"))
        return
    }

    jwtStr := strings.Split(jwtObj, "JWT ")[1]

    token, err := jwt.ParseWithClaims(jwtStr, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(configs.Default.Secret), nil
    })
    if err != nil {
        ctx.AbortWithError(401, err)
        return
    }
    claims, ok := token.Claims.(*JWTClaims)
    if !ok {
        ctx.AbortWithError(401, errors.New("test"))
        return
    }
    if err := token.Claims.Valid(); err != nil {
        ctx.AbortWithError(401, err)
        return
    }
    ctx.Set("USER_ID", claims.UserID)
    ctx.Next()
}

 

---

 

posted @ 2018-11-23 18:21  静静别跑  阅读(3419)  评论(0编辑  收藏  举报