MCPcopy Create free account
hub / github.com/Keats/jsonwebtoken / encode

Function encode

src/encoding.rs:160–178  ·  view source on GitHub ↗

Encode the header and claims given and sign the payload using the algorithm from the header and the key. If the algorithm given is RSA or EC, the key needs to be in the PEM format. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{encode, Algorithm, Header, EncodingKey}; #[derive(Debug, Serialize, Deserialize)] struct Claims { sub: String, company: String } let my_claims = Claims

(header: &Header, claims: &T, key: &EncodingKey)

Source from the content-addressed store, hash-verified

158/// let token = encode(&Header::default(), &my_claims, &EncodingKey::from_secret("secret".as_ref()).unwrap()).unwrap();
159/// ```
160pub fn encode<T: Serialize>(header: &Header, claims: &T, key: &EncodingKey) -> Result<String> {
161 if key.family != header.alg.family() {
162 return Err(new_error(ErrorKind::InvalidAlgorithm));
163 }
164
165 let signing_provider = (CryptoProvider::get_default().signer_factory)(&header.alg, key)?;
166
167 if signing_provider.algorithm() != header.alg {
168 return Err(new_error(ErrorKind::InvalidAlgorithm));
169 }
170
171 let encoded_header = b64_encode_part(&header)?;
172 let encoded_claims = b64_encode_part(claims)?;
173 let message = [encoded_header, encoded_claims].join(".");
174
175 let signature = b64_encode(signing_provider.try_sign(message.as_bytes())?);
176
177 Ok([message, signature].join("."))
178}

Callers

nothing calls this directly

Calls 8

new_errorFunction · 0.85
get_defaultFunction · 0.85
b64_encode_partFunction · 0.85
b64_encodeFunction · 0.85
as_bytesMethod · 0.80
familyMethod · 0.45
algorithmMethod · 0.45
try_signMethod · 0.45

Tested by

no test coverage detected