2023-09-29 07:41:01 +02:00
|
|
|
package jwtutil
|
2023-03-20 16:40:08 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jwa"
|
|
|
|
"github.com/lestrrat-go/jwx/v2/jwk"
|
2023-10-03 19:24:03 +02:00
|
|
|
"github.com/lestrrat-go/jwx/v2/jws"
|
2023-03-20 16:40:08 +01:00
|
|
|
"github.com/lestrrat-go/jwx/v2/jwt"
|
2023-10-02 23:05:18 +02:00
|
|
|
"github.com/oklog/ulid/v2"
|
2023-03-20 16:40:08 +01:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2023-09-29 07:41:01 +02:00
|
|
|
func SignedToken(key jwk.Key, signingAlgorithm jwa.SignatureAlgorithm, 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)
|
|
|
|
}
|
|
|
|
|
2023-10-02 23:05:18 +02:00
|
|
|
if err := token.Set(jwt.JwtIDKey, ulid.Make().String()); err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
2023-03-20 16:40:08 +01:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-29 07:41:01 +02:00
|
|
|
if err := token.Set(jwk.AlgorithmKey, signingAlgorithm); err != nil {
|
2023-03-20 16:40:08 +01:00
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
2023-09-29 07:41:01 +02:00
|
|
|
rawToken, err := jwt.Sign(token, jwt.WithKey(signingAlgorithm, key))
|
2023-03-20 16:40:08 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return rawToken, nil
|
|
|
|
}
|
2023-10-03 19:24:03 +02:00
|
|
|
|
|
|
|
func Parse(rawToken []byte, keySet jwk.Set) (jwt.Token, error) {
|
|
|
|
token, err := jwt.Parse(rawToken,
|
|
|
|
jwt.WithKeySet(keySet, jws.WithRequireKid(false)),
|
|
|
|
jwt.WithValidate(true),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.WithStack(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, nil
|
|
|
|
}
|