Nexus/pkg/nex/sec/jwt_writer.go

46 lines
842 B
Go
Raw Normal View History

2024-10-21 16:12:28 +00:00
package sec
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/golang-jwt/jwt/v5"
"os"
)
type JwtWriter struct {
key *rsa.PrivateKey
}
func NewJwtWriter(fp string) (*JwtWriter, error) {
rawKey, err := os.ReadFile(fp)
2024-10-21 16:12:28 +00:00
if err != nil {
return nil, err
}
block, _ := pem.Decode(rawKey)
2024-10-21 16:12:28 +00:00
if block == nil || block.Type != "PRIVATE KEY" {
return nil, fmt.Errorf("failed to decode PEM block containing private key")
}
anyPk, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
pk, ok := anyPk.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("not an RSA private key")
}
return &JwtWriter{
key: pk,
}, nil
}
func WriteJwt[T jwt.Claims](v *JwtWriter, in T) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodRS256, in)
return token.SignedString(v.key)
2024-10-21 16:12:28 +00:00
}