jwt 认证初步完成
This commit is contained in:
@@ -3,6 +3,10 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
)
|
||||
|
||||
@@ -19,3 +23,31 @@ func GetUserInfoFormCtx(ctx context.Context) UserInfo {
|
||||
}
|
||||
return UserInfo{UserId: uid}
|
||||
}
|
||||
|
||||
// 获取登录信息
|
||||
func GetUserInfoFormMapClaims(claims jwt.MapClaims) (*UserInfo, error) {
|
||||
if userid, ok := claims["userid"]; ok {
|
||||
uid, ok := userid.(float64)
|
||||
if !ok {
|
||||
err := errors.New(fmt.Sprint("parse uid form context err:", userid))
|
||||
logx.Error("parse uid form context err:", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &UserInfo{UserId: int64(uid)}, nil
|
||||
} else {
|
||||
err := errors.New(`userid not in claims`)
|
||||
logx.Error(`userid not in claims`)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func GenerateJwtToken(accessSecret string, accessExpire, nowSec int64, userid int) (string, error) {
|
||||
claims := make(jwt.MapClaims)
|
||||
claims["exp"] = nowSec + accessExpire
|
||||
claims["iat"] = nowSec
|
||||
claims["userid"] = userid
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
token.Claims = claims
|
||||
return token.SignedString([]byte(accessSecret))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user