主要针对jwt-go快速生成token。和如何取进行介绍,具体详情还请查看
github.com/dgrijalva/jwt-go 生成token
package mainimport ( "flag" "fmt" "github.com/dgrijalva/jwt-go" "github.com/micro/go-micro/config" "time" )type Config struct { Version string Hellostruct { Name string } Etcd struct { Addrs[]string UserName string Password string } }type User struct { Namestring `json:"name"` Password string `json:"password"` Tokenstruct { AccessToken string `json:"accessToken"` ExpiresAtint64`json:"expiresAt"` Timestampint64`json:"timestamp"` } }func main(){// 主要解析config.json配置文件,生成token没有用到 configFile := flag.String("f", "/go-gin-micro/config/config.json", "please use config.json") conf := new(Config) if err := config.LoadFile(*configFile); err != nil { return } if err := config.Scan(conf); err != nil { return } fmt.Println(conf) //md := map[string]string{ // "vector": "yang", //} user := &User{} claims := &jwt.StandardClaims{ ExpiresAt:time.Now().Add(30*time.Second).Unix(), // 过期时间,必须设置 Issuer:"wang",// 可不必设置,也可以填充用户名, } expired := time.Now().Add(148 * time.Hour).Unix() token := jwt.NewWithClaims(jwt.SigningMethodHS256,claims) //生成token accessToken, err := token.SignedString([]byte("vector.sign")) if err != nil { return } user.Token.ExpiresAt = expired user.Token.AccessToken = accessToken user.Token.Timestamp = time.Now().Unix()}
解析token
package mainimport ( "flag" "fmt" "github.com/dgrijalva/jwt-go" "time" )func InitC(token string){ authorization := toekn token,err := jwt.Parse(authorization, func(token *jwt.Token) (i interface{}, e error) { return []byte("vector.sign"),nil }) if err != nil { // 第一种 //if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { // fmt.Println("+++") // return //} //fmt.Println([]byte("vector.sign"))// 第二种 if err ,ok := err.(*jwt.ValidationError); ok { if err.Errors & jwt.ValidationErrorMalformed != 0 { return } if err.Errors & (jwt.ValidationErrorExpired | jwt.ValidationErrorNotValidYet) != 0 { fmt.Println(err) return } } return } finToken := token.Claims.(jwt.MapClaims)// 获取token里面的字段,如生成填入的username fmt.Println(finToken["iss"]) }
【golang|golang 之 jwt-go】
转载于:https://www.cnblogs.com/flash55/p/11397032.html