54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package service
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
// TokenConfig holds the configuration for the token service
|
|
type TokenConfig struct {
|
|
AppID string
|
|
AppKey string
|
|
SigExp int
|
|
}
|
|
|
|
// TokenService handles JWT token generation
|
|
type TokenService struct {
|
|
config TokenConfig
|
|
}
|
|
|
|
// NewTokenService creates a new instance of TokenService
|
|
func NewTokenService(config TokenConfig) *TokenService {
|
|
return &TokenService{
|
|
config: config,
|
|
}
|
|
}
|
|
|
|
// CreateSignature generates a JWT token
|
|
func (s *TokenService) CreateSignature() (string, error) {
|
|
// Get current time
|
|
now := time.Now().UTC()
|
|
// Calculate expiration time
|
|
expiresAt := now.Add(time.Duration(s.config.SigExp) * time.Second)
|
|
|
|
// Create claims
|
|
claims := jwt.MapClaims{
|
|
"iss": "your-issuer", // Optional: Issuer
|
|
"iat": now.Unix(), // Issued at time
|
|
"exp": expiresAt.Unix(), // Expiration time
|
|
"appId": s.config.AppID, // Custom claim
|
|
}
|
|
|
|
// Create token
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
// Sign and get the complete encoded token as a string
|
|
tokenString, err := token.SignedString([]byte(s.config.AppKey))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return tokenString, nil
|
|
}
|