使用JWT包生成token
详情看代码注释
// 记得引入jwt包
// import "github.com/dgrijalva/jwt-go"
// 这里定义的字段其实就是生成token串中的属性
type JwtCustomClaims struct {
jwt.StandardClaims // 包中自带的默认属性
Uid uint `json:"uid"` // 当前访问人uid 自定义添加一些自己需要的元素
}
// 生成token串
// 这里的参数一般为自己自定义的一些参数
func GenerateToken(userId uint, role int8) (string, error) {
// 这里使用的是自定义结构体的方式床架claims,也可以使用jwt.MapClaims结构体
/*
claims := jwt.MapClaims{} // 其实就是个map
claims["uid"] = userId
*/
claims := JwtCustomClaims{
jwt.StandardClaims{
ExpiresAt: int64(time.Now().Add(time.Minute * time.Duration(expire)).Unix()),
Issuer: config.GetConfig().Encrypt.EncryptIssuer,
},
userId,
role,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// 这里需要注意当使用jwt.SigningMethodHS256方式生成token串时,SignedString方法的参数应该是[]byte数组,其他方式也对key有着要求
tokenStr, err := token.SignedString([]byte(config.GetConfig().Encrypt.EncryptKey