# jwt
## jwt-go
```go
package jwtgo
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"time"
)
const (
// secretKey 加密key
secretKey = "Q6jhLn8vsD04WmAR"
)
// expTime token有效时间
var expTime = time.Now().Add(time.Hour * 2).Unix()
// JwtClaims 自定义 Claims 结构体
type JwtClaims struct {
// 按需求自定义下方参数
Id string
Name string
Role string
jwt.StandardClaims
}
// GenerateToken
// 利用JwtClaims生成token字符串
// 加密方式; SHA256
func GenerateToken(id, name, role string) (tokenStr string, err error) {
jwtClaims := &JwtClaims{
Id: id, //用户id
Name: name,
Role: role,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expTime,
//Issuer: issuer, //发行人
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtClaims)
tokenStr, err = token.SignedString([]byte(secretKey))
return
}
//ParseToken 解析token
func ParseToken(tokenString string) (*JwtClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method %v ", token.Header["alg"])
}
return []byte(secretKey), nil
})
if claims, ok := token.Claims.(*JwtClaims); ok && token.Valid {
return claims, nil
} else {
return nil, err
}
}
```
## 使用
```go
package main
import (
"fmt"
"gotoys/plugins/jwtgo"
"log"
)
func main() {
// 生成token
token, err := jwtgo.GenerateToken(
"cc6a6e14-2f11-4b61-b077-1b0f7b9c7944",
"xiao ming",
"administrator")
if err != nil {
log.Printf("%v", err)
} else {
fmt.Printf("token:%s\n", token)
}
// 解析token
jwtClaims, err := jwtgo.ParseToken(token)
if err != nil {
log.Printf("%v", err)
} else {
fmt.Printf("id:%s\nname:%s\nrole:%s\nexp:%d", jwtClaims.Id, jwtClaims.Name, jwtClaims.Role, jwtClaims.ExpiresAt)
}
}
```
打印结果
```bash
token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6ImNjNmE2ZTE0LTJmMTEtNGI2MS1iMDc3LTFiMGY3YjljNzk0NCIsIk5hbWUiOiJ4aWFvIG1pbmciLCJSb2xlIjoiYWRtaW5pc3RyYXRvciIsImV4cCI6MTYwODk5Nzk5NH0.RuPNtNzoUQiaRb2qQYgfR2FBoi4rpox3kzMdO_WgUt0
id:cc6a6e14-2f11-4b61-b077-1b0f7b9c7944
name:xiao ming
role:administrator
exp:1608997994
```