|
|
|
|
package jwt
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"git.noahlan.cn/noahlan/ntool/ndef"
|
|
|
|
|
"git.noahlan.cn/noahlan/ntool/nrandom"
|
|
|
|
|
"git.noahlan.cn/noahlan/ntool/nstr"
|
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
|
|
|
"strconv"
|
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type (
|
|
|
|
|
ClaimStrings = jwt.ClaimStrings
|
|
|
|
|
Claims = jwt.Claims
|
|
|
|
|
SigningMethod = jwt.SigningMethod
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type (
|
|
|
|
|
Option struct {
|
|
|
|
|
Key string
|
|
|
|
|
Val any
|
|
|
|
|
}
|
|
|
|
|
Token struct {
|
|
|
|
|
AccessToken string
|
|
|
|
|
ExpiresAt int64
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func WithOption(key string, val any) Option {
|
|
|
|
|
return Option{key, val}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func WithRoles(codes []string) Option {
|
|
|
|
|
return WithOption(KeyRoles, nstr.JoinAny(ndef.CommaStr, codes))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func WithID(id string) Option {
|
|
|
|
|
return WithOption("jti", id)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func WithRandID() Option {
|
|
|
|
|
return WithID(nrandom.SnowflakeIdStr())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func WithAudience(val jwt.ClaimStrings) Option {
|
|
|
|
|
return WithOption("aud", val)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewJwtToken(secretKey string, uid, expiresIn int64, opts ...Option) (Token, error) {
|
|
|
|
|
iat := time.Now().Unix()
|
|
|
|
|
claims := make(jwt.MapClaims)
|
|
|
|
|
claims["iat"] = iat // 签发时间
|
|
|
|
|
claims["exp"] = iat + expiresIn // 过期时间
|
|
|
|
|
claims["iss"] = "lan6995@gmail.com" // 签发者
|
|
|
|
|
claims["sub"] = strconv.FormatInt(uid, 10) // subject 面向用户
|
|
|
|
|
//claims["aud"] = "" // 接收jwt的
|
|
|
|
|
claims["nbf"] = iat // 在xx时间之前,该jwt不可用
|
|
|
|
|
claims[KeyUserId] = uid // 自定义字段 uid
|
|
|
|
|
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
|
claims[opt.Key] = opt.Val
|
|
|
|
|
}
|
|
|
|
|
token := jwt.New(jwt.SigningMethodHS256)
|
|
|
|
|
token.Claims = claims
|
|
|
|
|
jwtStr, err := token.SignedString([]byte(secretKey))
|
|
|
|
|
|
|
|
|
|
result := Token{
|
|
|
|
|
AccessToken: jwtStr,
|
|
|
|
|
ExpiresAt: iat + expiresIn,
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
return result, err
|
|
|
|
|
}
|
|
|
|
|
return result, nil
|
|
|
|
|
}
|