golang JWT(Json Web Tocken)

什么是JWT,相信大家都熟悉了,我直接上代码了,有不懂的地方直接参考什么是JWT

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "github.com/dgrijalva/jwt-go"
    "fmt"
    "strconv"
    "time"
)

//req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))

func main() {
    //fmt.Println(ComputeHmac256("Message", "secret"))
    tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
    hmacSecret := []byte("secret")
    ParseHmac(tokenString, hmacSecret)

}

 NewHmac creating, signing, and encoding a JWT token using the HMAC signing method
//func NewHmac() {
//  // Create a new token object, specifying signing method and the claims
//  // you would like it to contain.
//  token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
//      "foo": "bar",
//      "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
//  })
//
//  // Sign and get the complete encoded token as a string using the secret
//  tokenString, err := token.SignedString(hmacSampleSecret)
//
//  fmt.Println(tokenString, err)
//  // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>
//}

// ParseHmac parsing and validating a token using the HMAC signing method
func ParseHmac(tokenString string, hmacSecret []byte) bool {

    // Parse takes the token string and a function for looking up the key. The latter is especially
    // useful if you use multiple keys for your application.  The standard is to use 'kid' in the
    // head of the token to identify which key to use, but the parsed token (head and claims) is provided
    // to the callback, providing flexibility.
    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        // Don't forget to validate the alg is what you expect:
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
        }

        // hmacSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
        return hmacSecret, nil
    })

    fmt.Printf("alg=[%s]\n", token.Header["alg"])

    if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {

        fmt.Println(claims["sub"], claims["name"], claims["admin"])

        sub, _ := strconv.ParseInt(fmt.Sprintf("%s", claims["sub"]), 10, 64)

        now, _ := strconv.ParseInt(fmt.Sprintf("%s", time.Now()), 10, 64)

        if now-sub > 0 {
            return true
        }

        fmt.Printf("Error The Tocken is lose efficacy:%v\n", token)

        return false

    }

    fmt.Println("Error token is error=", err)

    return false

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值