You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
853 B
36 lines
853 B
package jwt
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/rs/xid"
|
|
"zestack.dev/env"
|
|
)
|
|
|
|
// Generate 生成令牌
|
|
func Generate(claims Claims) (string, error) {
|
|
if claims.ID == "" {
|
|
claims.ID = xid.New().String()
|
|
}
|
|
if claims.Issuer == "" {
|
|
claims.Issuer = env.String("JWT_ISSUER")
|
|
}
|
|
if claims.Subject == "" {
|
|
claims.Issuer = env.String("JWT_SUBJECT")
|
|
}
|
|
if claims.Audience == nil {
|
|
claims.Audience = env.List("JWT_AUDIENCE", []string{"*"})
|
|
}
|
|
if claims.ExpiresAt == nil {
|
|
ttl := env.Duration("JWT_TTL", time.Hour)
|
|
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(ttl))
|
|
}
|
|
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
|
signedToken, err := token.SignedString(privateKey)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString([]byte(signedToken)), nil
|
|
}
|
|
|