A go (or ‘golang’ for search engine friendliness) implementation of JSON Web Tokens.
译文:一个Go(或“Golang”表示搜索引擎友好性)JSON Web Tokens实现。
文档
安装
go get github.com/golang-jwt/jwt/v4
示例:生成jwt
package main import ( "fmt" "github.com/golang-jwt/jwt/v4" ) func main() { // 秘钥 secret := []byte("key") // 参数 token := jwt.NewWithClaims( jwt.SigningMethodHS256, jwt.MapClaims{ "name": "Tom", "age": 20, }) tokenString, _ := token.SignedString(secret) fmt.Println(tokenString) // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZ2UiOjIwLCJuYW1lIjoiVG9tIn0.bU-8W6kUQM55ZT-mviisDnGja2nOmvYXkyWirrFMUf0 }
示例:解析jwt
package main import ( "fmt" "github.com/golang-jwt/jwt/v4" ) func main() { // 秘钥 secret := []byte("key") tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZ2UiOjIwLCJuYW1lIjoiVG9tIn0.bU-8W6kUQM55ZT-mviisDnGja2nOmvYXkyWirrFMUf0" token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { return secret, nil }) claims, _ := token.Claims.(jwt.MapClaims) fmt.Printf("claims: %v\n", claims) // claims: map[age:20 name:Tom] }