Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust: wrapper for jsonwebtoken and serde Deserialize

I am writing a Rust wrapper to sign and decode a given struct.

The create_token method seems to work: but the decode_token return an error on compile time about the lifetimes:

use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};

const JWT_SECRET: &[u8] = b"secret";

pub struct TokenService;

impl<'de> TokenService {
  pub fn create_token<T: Serialize>(data: T) -> String {
    let header = Header::new(Algorithm::HS512);

    let token = encode(&header, &data, &EncodingKey::from_secret(JWT_SECRET)).unwrap();

    token
  }

  pub fn decode_token<T: Deserialize<'de>>(data: &str) -> T {
    let decoded = decode::<T>(&data, &DecodingKey::from_secret(JWT_SECRET), &Validation::new(Algorithm::HS512)).unwrap();
    //                     ^ Error here
    decoded
  }
}

the trait bound `for<'de> T: types::errors::_::_serde::Deserialize<'de>` is not satisfied

the trait `for<'de> types::errors::_::_serde::Deserialize<'de>` is not implemented for `T`

note: required because of the requirements on the impl of `rocket::serde::DeserializeOwned` for `T`

I am not sure where should I add this missing lifetime. Any help will be welcome.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Usually T would need to be constrained to DeserializeOwned:

pub fn decode_token<T: DeserializeOwned>(data: &str) -> T {
    let decoded = decode::<T>(&data, &DecodingKey::from_secret(JWT_SECRET), &Validation::new(Algorithm::HS512)).unwrap();
    decoded
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading