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

Function encode

src/encoding.rs:151–169  ·  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

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

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