pub struct JwtSigner { /* private fields */ }Expand description
A JWT signer backed by a Web Crypto CryptoKey.
JwtSigner owns an imported key and the SubtleCrypto handle used to
sign with it. Create one with JwtSigner::new and call sign as
many times as needed — importing the key is the expensive part, signing
is cheap.
§Example
use worker_jwt::{Algorithm, Claims, JwtSigner};
let signer = JwtSigner::new(Algorithm::Rs256, pem).await?;
let claims = Claims::builder()
.issuer("example-app")
.expires_at(1_750_000_000)
.build();
let token = signer.sign(&claims).await?;Implementations§
Source§impl JwtSigner
impl JwtSigner
Sourcepub async fn new(algorithm: Algorithm, key_data: &[u8]) -> Result<Self>
pub async fn new(algorithm: Algorithm, key_data: &[u8]) -> Result<Self>
Imports key_data into a Web Crypto CryptoKey and returns a signer.
The expected format of key_data depends on the algorithm:
Algorithm::Rs256: PKCS#8 PEM (-----BEGIN PRIVATE KEY-----) or PKCS#1 PEM (-----BEGIN RSA PRIVATE KEY-----). GitHub App private keys ship as PKCS#1 and are accepted without conversion.Algorithm::Es256: PKCS#8 PEM only. Convert SEC1 PEMs (-----BEGIN EC PRIVATE KEY-----) withopenssl pkcs8 -topk8 -nocrypt -in in.pem -out out.pemfirst.Algorithm::Hs256: raw shared-secret bytes.
§Errors
Returns JwtError::InvalidPem if PEM parsing fails, or
JwtError::CryptoError if Web Crypto rejects the key material
(wrong algorithm, corrupted DER, unsupported curve, etc.).
Sourcepub async fn sign(&self, claims: &Claims) -> Result<String>
pub async fn sign(&self, claims: &Claims) -> Result<String>
Signs claims and returns the encoded JWT header.payload.signature.
The header is fixed to {"alg":"<algorithm>","typ":"JWT"}. The
payload is produced by serializing claims to JSON (skipping
None fields and flattening
extra). Both parts are base64url-encoded
without padding as required by RFC 7519.
§Errors
Returns JwtError::SerializationError if the claims cannot be
serialized, or JwtError::CryptoError if the underlying Web
Crypto sign call fails.