什么是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
}