fix
This commit is contained in:
51
utils/ldap_lib/jwt_parse.go
Normal file
51
utils/ldap_lib/jwt_parse.go
Normal file
@@ -0,0 +1,51 @@
|
||||
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, password 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(password))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "Bearer " + token, nil
|
||||
}
|
||||
|
||||
// 解释token
|
||||
func (l *Ldap) ParseJwtToken(token, password 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(password), 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
|
||||
}
|
||||
Reference in New Issue
Block a user