2023-09-20 16:55:49 +02:00
|
|
|
package jwt
|
2023-03-20 16:40:08 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jwa"
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jwk"
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jwt"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2023-09-20 16:55:49 +02:00
|
|
|
func GenerateSignedToken(algo jwa.KeyAlgorithm, key jwk.Key, claims map[string]any) ([]byte, error) {
|
2023-03-20 16:40:08 +01:00
|
|
|
token := jwt.New()
|
|
|
|
|
|
|
|
if err := token.Set(jwt.NotBeforeKey, time.Now()); err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
for key, value := range claims {
|
|
|
|
if err := token.Set(key, value); err != nil {
|
|
|
|
return nil, errors.Wrapf(err, "could not set claim '%s' with value '%v'", key, value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := token.Set(jwk.AlgorithmKey, jwa.HS256); err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
rawToken, err := jwt.Sign(token, jwt.WithKey(algo, key))
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return rawToken, nil
|
|
|
|
}
|