Sign tokens
Per the specification:
JSON Web Signature (JWS) represents content secured with digital signatures or Message Authentication Codes (MACs) using JSON-based data structures. Cryptographic algorithms and identifiers for use with this specification are described in the separate JSON Web Algorithms (JWA) specification and an IANA registry defined by that specification. Related encryption capabilities are described in the separate JSON Web Encryption (JWE) specification.
Every signature algorithm is based on a private/public key pair. Most algorithms use asymmetric keys (where the public key only contains a subset of the private key information): the private key is kept secret to the producer, while the recipients can only access the public key. Some algorithms, however, use symmetric keys (like HMAC): in this case, the same key is shared by the producer and recipient, and both can either sign or verify tokens.
package main
import (
"context"
"github.com/a-novel-kit/jwt"
"github.com/a-novel-kit/jwt/jws"
)
func main() {
// HMAC Signatures require a symmetric HMAC key.
// Refer to the JWK package for hints to generate one.
var secretKey []byte
signer := jws.NewHMACSigner(secretKey, jws.HS256)
producer := jwt.NewProducer(jwt.ProducerConfig{
Plugins: []jwt.ProducerPlugin{signer},
})
claims := map[string]any{"foo": "bar"}
token, _ := producer.Issue(context.Background(), claims, nil)
}
Available presets for HMAC signatures are:
Preset | Target "alg" |
---|---|
jws.HS256 | HS256 |
jws.HS384 | HS384 |
jws.HS512 | HS512 |
Using auto-sourcing
Passing keys manually and creating a new signer for each secret key can be cumbersome. To avoid this, you can use an alternate version that relies on a dynamic source of keys.
package main
import (
"context"
"github.com/a-novel-kit/jwt"
"github.com/a-novel-kit/jwt/jwk"
"github.com/a-novel-kit/jwt/jws"
)
func main() {
// See JWK documentation for how to configure the source.
// Preset for the source MUST match those of the signer.
source := jwk.NewHMACSource(config, jwk.HS256)
signer := jws.NewSourcedHMACSigner(source, jws.HS256)
producer := jwt.NewProducer(jwt.ProducerConfig{
Plugins: []jwt.ProducerPlugin{signer},
})
claims := map[string]any{"foo": "bar"}
token, _ := producer.Issue(context.Background(), claims, nil)
}
Available presets for HMAC signatures are:
Preset | Target "alg" | Source preset |
---|---|---|
jws.HS256 | HS256 | jwk.HS256 |
jws.HS384 | HS384 | jwk.HS384 |
jws.HS512 | HS512 | jwk.HS512 |