Rust:jsonwebtoken 和 serde Deserialize 的包装器
Rust: wrapper for jsonwebtoken and serde Deserialize
我正在编写一个 Rust 包装器来对给定结构进行签名和解码。
create_token
方法似乎有效:但是 decode_token
return 关于生命周期的编译时间错误:
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`
我不知道应该在哪里添加这个缺失的生命周期。欢迎任何帮助。
通常 T
需要限制为 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
}
我正在编写一个 Rust 包装器来对给定结构进行签名和解码。
create_token
方法似乎有效:但是 decode_token
return 关于生命周期的编译时间错误:
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`
我不知道应该在哪里添加这个缺失的生命周期。欢迎任何帮助。
通常 T
需要限制为 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
}