49 lines
1.0 KiB
Go
49 lines
1.0 KiB
Go
// Copyright 2024 Patial Tech (Ankit Patial).
|
|
// All rights reserved.
|
|
|
|
package jwt
|
|
|
|
import (
|
|
"crypto/ed25519"
|
|
"errors"
|
|
"log"
|
|
"maps"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func Sign(key ed25519.PrivateKey, claims map[string]any, issuer string, d time.Duration) (string, error) {
|
|
cl := jwt.MapClaims{
|
|
"iss": issuer,
|
|
"iat": jwt.NewNumericDate(time.Now().UTC()),
|
|
"exp": jwt.NewNumericDate(time.Now().Add(d)),
|
|
}
|
|
maps.Copy(cl, claims)
|
|
|
|
t := jwt.NewWithClaims(jwt.SigningMethodEdDSA, cl)
|
|
return t.SignedString(key)
|
|
}
|
|
|
|
func Parse(key ed25519.PrivateKey, tokenString string, issuer string) (jwt.MapClaims, error) {
|
|
token, err := jwt.Parse(
|
|
tokenString,
|
|
func(token *jwt.Token) (any, error) {
|
|
return key.Public(), nil
|
|
},
|
|
jwt.WithValidMethods([]string{jwt.SigningMethodEdDSA.Alg()}),
|
|
jwt.WithIssuer(issuer),
|
|
jwt.WithIssuedAt(),
|
|
jwt.WithExpirationRequired(),
|
|
)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok {
|
|
return claims, nil
|
|
} else {
|
|
return nil, errors.New("no claims found")
|
|
}
|
|
}
|