go + jwt + 权限认证

时间:2023-02-23 09:00:14


流程

​http://blog.fatedier.com/2020/03/28/golang-jwt/​

 

1.生成的token长度和jwtCustomClaims(playload)大小相关

2.支持jwt.SigningMethodHS256和jwt.SigningMethodES256,jwt.SigningMethodRS256等加密方法

package main
import(
"github.com/dgrijalva/jwt-go"
//"time"
"reflect"
"fmt"
log "github.com/thinkboy/log4go"
)

type TokenPlayload struct{
AccountId string `json:"account_id"` //结构体成员首字母尽量大写,否则在其他包中就无法引用
Terminal string `json:"terminal"`
GroupId int64 `json:"group"`
}

type jwtCustomClaims struct {
jwt.StandardClaims
TokenPlayload
}

func CreateToken(SecretKey []byte, issuer string, tokenPlayload *TokenPlayload) (tokenString string, err error) {
claims := &jwtCustomClaims{
jwt.StandardClaims{
//ExpiresAt: int64(time.Now().Add(time.Hour * 72).Unix()),
// Issuer: issuer,
},
*tokenPlayload,
}
log.Info(claims)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err = token.SignedString(SecretKey)
return
}

func ParseToken(tokenSrt string, SecretKey []byte) (claims jwt.Claims, err error) {
var token *jwt.Token
token, err = jwt.Parse(tokenSrt, func(*jwt.Token) (interface{}, error) {
return SecretKey, nil
})
claims = token.Claims
return
}

func main(){
log.Info("test begin")
SecretKey := "123"
tokenPlayload := TokenPlayload{
"5d5a92150d60a5726471cd3a",
"mobile",
5,
}
tokenPlayload.AccountId = "123"
token, _ := CreateToken([]byte(SecretKey), "YDQ", &tokenPlayload)
log.Info(token)
claims, _ := ParseToken(token, []byte(SecretKey))
v := reflect.ValueOf(claims)
if v.Kind() == reflect.Map {
for _, k := range v.MapKeys() {
value := v.MapIndex(k)
key := fmt.Sprintf("%s", k.Interface())
strValue := fmt.Sprintf("%v", value.Interface()) //使用%v 兼容value是所有类型,不仅仅是字符串
log.Info("%s : %s", key, strValue)
}
}
log.Info(claims)
}