golang 生成token并解析
时间: 2024-01-18 08:02:41 浏览: 155
生成Token:
```go
package main
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
func main() {
// set token claims
claims := jwt.MapClaims{}
claims["authorized"] = true
claims["user_id"] = "1234"
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
// create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// set secret key
secret := "my_secret_key"
// sign token with secret key
signedToken, err := token.SignedString([]byte(secret))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(signedToken)
}
```
解析Token:
```go
package main
import (
"fmt"
"github.com/dgrijalva/jwt-go"
)
func main() {
// set secret key
secret := "my_secret_key"
// sample token string
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ0ZXN0IiwidXNlcl9pZCI6IjEyMzQiLCJleHAiOjE2MTUzODIwMzN9.P4nJ6UdLjUkC6BVmTQlJm6jKBO6wZKmJnR_8gCJb9XQ"
// parse token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// validate signing method
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// return secret key
return []byte(secret), nil
})
if err != nil {
fmt.Println(err)
return
}
// validate token claims
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Println(claims["authorized"], claims["user_id"])
} else {
fmt.Println(err)
}
}
```
阅读全文