rano/util/jwt/jwt.go
2024-11-19 10:40:30 +05:30

59 lines
1.4 KiB
Go

// Copyright 2024 Patial Tech. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jwt
import (
"crypto/ed25519"
"fmt"
"time"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
j "github.com/lestrrat-go/jwx/v2/jwt"
)
func Sign(key ed25519.PrivateKey, claims map[string]interface{}, issuer string, d time.Duration) (string, error) {
prv, err := jwk.FromRaw(key)
if err != nil {
return "", fmt.Errorf("failed to create JWK, %w", err)
}
builder := j.NewBuilder().
Issuer(issuer).
IssuedAt(time.Now()).
Expiration(time.Now().Add(d))
for k, v := range claims {
builder = builder.Claim(k, v)
}
token, err := builder.Build()
signed, err := j.Sign(token, j.WithKey(jwa.EdDSA, prv))
if err != nil {
return "", fmt.Errorf("failed to generate signed payload, %w", err)
}
return string(signed), nil
}
func Parse(key ed25519.PrivateKey, payload string) (j.Token, error) {
prv, err := jwk.FromRaw(key)
if err != nil {
return nil, fmt.Errorf("failed to create JWK, %w", err)
}
pub, err := jwk.PublicKeyOf(prv)
if err != nil {
return nil, fmt.Errorf("failed on jwk.FromRaw, %w", err)
}
token, err := j.Parse([]byte(payload), j.WithKey(jwa.EdDSA, pub))
if err != nil {
return nil, fmt.Errorf("failed on jwk.FromRaw, %w", err)
}
return token, nil
}