jsonwebtoken/src/lib.rs

59 lines
1.8 KiB
Rust
Raw Normal View History

2015-10-31 11:37:15 -04:00
//! Create and parses JWT (JSON Web Tokens)
//!
2017-04-13 03:36:32 -04:00
//! Documentation: [stable](https://docs.rs/jsonwebtoken/)
2017-04-12 21:08:07 -04:00
#![deny(missing_docs)]
2017-02-22 02:45:28 -05:00
2019-06-16 11:51:43 -04:00
mod algorithms;
2019-11-14 13:43:43 -05:00
/// Lower level functions, if you want to do something other than JWTs
pub mod crypto;
2019-11-09 06:42:40 -05:00
mod decoding;
2019-11-14 13:43:43 -05:00
/// All the errors that can be encountered while encoding/decoding JWTs
2015-10-31 11:37:15 -04:00
pub mod errors;
mod header;
2019-11-14 13:43:43 -05:00
mod pem;
2017-02-22 02:45:28 -05:00
mod serialization;
2017-04-11 01:41:44 -04:00
mod validation;
2019-06-16 11:51:43 -04:00
pub use algorithms::Algorithm;
2019-11-14 13:43:43 -05:00
pub use decoding::{
dangerous_unsafe_decode, decode, decode_header, decode_rsa_components, TokenData,
};
pub use header::Header;
2018-10-28 14:58:35 -04:00
pub use validation::Validation;
2017-04-13 03:36:32 -04:00
use serde::ser::Serialize;
2019-11-09 06:42:40 -05:00
use crate::errors::Result;
2019-11-11 14:16:34 -05:00
use crate::serialization::b64_encode_part;
2017-04-13 03:36:32 -04:00
2019-11-14 13:43:43 -05:00
/// 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.
2017-04-13 03:36:32 -04:00
///
2019-11-09 06:42:40 -05:00
/// ```rust
/// use serde::{Deserialize, Serialize};
2017-04-13 03:36:32 -04:00
/// use jsonwebtoken::{encode, Algorithm, Header};
///
2019-11-09 06:42:40 -05:00
/// #[derive(Debug, Serialize, Deserialize)]
2017-04-13 03:36:32 -04:00
/// struct Claims {
/// sub: String,
/// company: String
/// }
///
/// let my_claims = Claims {
/// sub: "b@b.com".to_owned(),
/// company: "ACME".to_owned()
/// };
///
/// // my_claims is a struct that implements Serialize
/// // This will create a JWT using HS256 as algorithm
/// let token = encode(&Header::default(), &my_claims, "secret".as_ref()).unwrap();
2017-04-13 03:36:32 -04:00
/// ```
pub fn encode<T: Serialize>(header: &Header, claims: &T, key: &[u8]) -> Result<String> {
2019-11-11 14:16:34 -05:00
let encoded_header = b64_encode_part(&header)?;
let encoded_claims = b64_encode_part(&claims)?;
2019-11-09 06:42:40 -05:00
let message = [encoded_header.as_ref(), encoded_claims.as_ref()].join(".");
2019-11-14 13:43:43 -05:00
let signature = crypto::sign(&*message, key, header.alg)?;
2017-04-13 03:36:32 -04:00
2019-11-09 06:42:40 -05:00
Ok([message, signature].join("."))
}