pub fn jwt_encode<T>(body: &T) -> Result<String>where
T: Serialize,Expand description
Creates a signed JWT token from the provided claims.
This function serializes the claims data and creates a signed JWT token using the configured signing algorithm and secret. The resulting token can be used for authentication across EJ services.
§Arguments
body- Claims data to encode in the token (must be serializable)
§Returns
Ok(String)- Base64-encoded JWT tokenErr(Error)- Token creation or serialization errors
§Security Notes
- Claims are not encrypted, only signed for integrity
- Include expiration claims to prevent token replay attacks
- Keep payload minimal to reduce token size and attack surface
§Example
use ej_auth::jwt::{jwt_encode, jwt_decode};
use serde::{Serialize, Deserialize};
use std::env;
unsafe { env::set_var("JWT_SECRET", "MySuperSecret"); }
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct BuilderClaims {
builder_id: String,
exp: usize,
}
let claims = BuilderClaims {
builder_id: "builder-001".to_string(),
exp: 4118335200,
};
let token = jwt_encode(&claims).unwrap();
let token_data = jwt_decode::<BuilderClaims>(&token).unwrap();
assert_eq!(claims, token_data.claims);