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.
>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
}