fusenapi/utils/ldap_lib/jwt_parse.go
laodaming 3c6aadb253 fix
2023-11-21 18:10:30 +08:00

54 lines
1.2 KiB
Go

package ldap_lib
import (
"encoding/json"
"errors"
"github.com/golang-jwt/jwt"
"time"
)
type UserInfo struct {
UserDN string `json:"user_dn"`
UserId int64 `json:"user_id"`
}
// 生成token
func (l *Ldap) GenJwtToken(userId, expireTime int64, userDN, secret string) (token string, err error) {
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_dn": userDN,
"user_id": userId,
"exp": time.Now().Add(time.Second * time.Duration(expireTime)).Unix(), //过期时间
"iss": "fusen",
})
token, err = t.SignedString([]byte(secret))
if err != nil {
return "", err
}
return "Bearer " + token, nil
}
// 解释token
func (l *Ldap) ParseJwtToken(token, secret string) (UserInfo, error) {
if len(token) <= 7 || token[:7] != "Bearer " {
return UserInfo{}, errors.New("无效的token")
}
token = token[7:]
t, err := jwt.ParseWithClaims(token, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
return UserInfo{}, err
}
d, err := json.Marshal(t.Claims)
if err != nil {
return UserInfo{}, err
}
var userInfo UserInfo
if err = json.Unmarshal(d, &userInfo); err != nil {
return UserInfo{}, err
}
return userInfo, nil
}
//