JwtConfig

Struct JwtConfig 

Source
pub struct JwtConfig {
    pub secret: String,
    pub expire_days: i64,
}
Expand description

JWT配置结构

Fields§

§secret: String

JWT密钥

§expire_days: i64

过期时间(天数)

Implementations§

Source§

impl JwtConfig

Source

pub fn new(secret: impl Into<String>, expire_days: i64) -> Self

创建新的JWT配置

Examples found in repository?
examples/jwt_usage.rs (line 73)
69fn example_custom_config() -> Result<()> {
70    println!("2. 使用自定义配置:");
71
72    // 创建自定义配置
73    let config = JwtConfig::new("my_super_secret_key_2024", 30); // 30天过期
74    let jwt_manager = JwtManager::new(config);
75
76    let session_data = SessionData {
77        user_id: "user456".to_string(),
78        permissions: vec!["read".to_string(), "write".to_string(), "admin".to_string()],
79        login_time: chrono::Utc::now().timestamp(),
80    };
81
82    // 使用自定义配置生成token
83    let token = jwt_manager.generate_token(&session_data)?;
84    println!("   自定义配置生成的token: {}...", &token[..50]);
85
86    // 使用同样的管理器验证token
87    let decoded_session: SessionData = jwt_manager.verify_token(&token)?;
88    println!("   解析出的会话数据: {:?}", decoded_session);
89
90    assert_eq!(session_data, decoded_session);
91    println!("   ✓ 自定义配置验证通过\n");
92
93    Ok(())
94}
95
96fn example_different_payloads() -> Result<()> {
97    println!("3. 不同类型的payload支持:");
98
99    // 字符串payload
100    let simple_data = "Hello JWT World!";
101    let token1 = generate_token(&simple_data, JwtConfig::default())?;
102    let decoded_string: String = verify_token(&token1)?;
103    println!("   字符串payload: {} -> {}", simple_data, decoded_string);
104
105    // 数字payload
106    let number_data = 42i32;
107    let token2 = generate_token(&number_data, JwtConfig::default())?;
108    let decoded_number: i32 = verify_token(&token2)?;
109    println!("   数字payload: {} -> {}", number_data, decoded_number);
110
111    // 复杂结构体
112    #[derive(Serialize, Deserialize, Debug, PartialEq)]
113    struct ComplexData {
114        name: String,
115        values: Vec<i32>,
116        metadata: std::collections::HashMap<String, String>,
117    }
118
119    let mut metadata = std::collections::HashMap::new();
120    metadata.insert("version".to_string(), "1.0".to_string());
121    metadata.insert("env".to_string(), "production".to_string());
122
123    let complex_data = ComplexData {
124        name: "test_data".to_string(),
125        values: vec![1, 2, 3, 4, 5],
126        metadata,
127    };
128
129    let token3 = generate_token(&complex_data, JwtConfig::default())?;
130    let decoded_complex: ComplexData = verify_token(&token3)?;
131    println!("   复杂结构体payload: {:?}", decoded_complex);
132
133    assert_eq!(complex_data, decoded_complex);
134    println!("   ✓ 不同类型payload验证通过\n");
135
136    Ok(())
137}
138
139fn example_error_handling() -> Result<()> {
140    println!("4. 错误处理示例:");
141
142    // 无效的token
143    let invalid_token = "invalid.jwt.token";
144    match verify_token::<User>(invalid_token) {
145        Ok(_) => println!("   意外:无效token被接受了"),
146        Err(e) => println!("   ✓ 无效token正确被拒绝: {}", e),
147    }
148
149    // 不同密钥的token
150    let config1 = JwtConfig::new("secret1", 7);
151    let config2 = JwtConfig::new("secret2", 7);
152    let manager1 = JwtManager::new(config1);
153    let manager2 = JwtManager::new(config2);
154
155    let user = User {
156        id: "test".to_string(),
157        username: "test_user".to_string(),
158        email: "test@example.com".to_string(),
159        role: "user".to_string(),
160    };
161
162    let token = manager1.generate_token(&user)?;
163    match manager2.verify_token::<User>(&token) {
164        Ok(_) => println!("   意外:不同密钥的token被接受了"),
165        Err(e) => println!("   ✓ 不同密钥的token正确被拒绝: {}", e),
166    }
167
168    println!("   ✓ 错误处理验证完成\n");
169
170    Ok(())
171}
More examples
Hide additional examples
examples/error_handling.rs (line 34)
30fn example_jwt_error_handling() -> Result<()> {
31    println!("1. JWT错误处理:");
32
33    // 测试无效密钥
34    let empty_config = JwtConfig::new("", 7); // 空密钥
35    let manager = JwtManager::new(empty_config);
36
37    let user = User {
38        id: "123".to_string(),
39        username: "test_user".to_string(),
40        email: "test@example.com".to_string(),
41        role: "user".to_string(),
42    };
43
44    match manager.generate_token(&user) {
45        Ok(_) => println!("   意外:空密钥应该失败"),
46        Err(ClamberError::JwtKeyError { details }) => {
47            println!("   ✓ 正确检测到密钥错误: {}", details);
48        }
49        Err(e) => println!("   ? 其他错误: {}", e),
50    }
51
52    // 测试无效token验证
53    let valid_config = JwtConfig::new("valid_secret", 7);
54    let valid_manager = JwtManager::new(valid_config);
55
56    match valid_manager.verify_token::<User>("invalid.jwt.token") {
57        Ok(_) => println!("   意外:无效token应该失败"),
58        Err(ClamberError::JwtVerifyError { details }) => {
59            println!("   ✓ 正确检测到JWT验证错误: {}", details);
60        }
61        Err(e) => println!("   ? 其他JWT错误: {}", e),
62    }
63
64    // 测试不同类型的错误处理
65    let config1 = JwtConfig::new("secret1", 7);
66    let config2 = JwtConfig::new("secret2", 7);
67    let manager1 = JwtManager::new(config1);
68    let manager2 = JwtManager::new(config2);
69
70    let token = manager1.generate_token(&user)?;
71
72    match manager2.verify_token::<User>(&token) {
73        Ok(_) => println!("   意外:不同密钥应该失败"),
74        Err(ClamberError::JwtVerifyError { details }) => {
75            println!("   ✓ 正确检测到密钥不匹配: {}", details);
76        }
77        Err(e) => println!("   ? 其他错误: {}", e),
78    }
79
80    println!();
81    Ok(())
82}
83
84fn example_success_case() -> Result<()> {
85    println!("2. 成功案例:");
86
87    let user = User {
88        id: "456".to_string(),
89        username: "success_user".to_string(),
90        email: "success@example.com".to_string(),
91        role: "admin".to_string(),
92    };
93
94    // 使用便利函数
95    let token = generate_token(&user, JwtConfig::default()).map_err(|e| {
96        println!("   生成token失败: {}", e);
97        e
98    })?;
99
100    println!("   ✓ 成功生成token");
101
102    // 检查有效性
103    if is_valid_token(&token) {
104        println!("   ✓ Token有效性验证通过");
105    } else {
106        println!("   ✗ Token无效");
107    }
108
109    // 验证并解析
110    let decoded_user: User = verify_token(&token).map_err(|e| {
111        println!("   验证token失败: {}", e);
112        e
113    })?;
114
115    println!("   ✓ 成功验证并解析token");
116    println!("   ✓ 用户数据: {:?}", decoded_user);
117
118    assert_eq!(user, decoded_user);
119    println!("   ✓ 数据一致性验证通过");
120
121    println!();
122    Ok(())
123}
124
125// 展示如何在实际应用中处理错误
126fn demonstrate_error_handling_patterns() {
127    println!("   演示不同的错误处理模式:");
128
129    // 模式1:具体错误类型处理
130    println!("\n   模式1:具体错误类型匹配");
131    let invalid_token = "invalid.token";
132    match verify_token::<User>(invalid_token) {
133        Ok(user) => println!("   用户验证成功: {:?}", user),
134        Err(ClamberError::JwtExpiredError) => {
135            println!("   → Token已过期,请重新登录");
136        }
137        Err(ClamberError::JwtVerifyError { details }) => {
138            println!("   → Token验证失败: {}", details);
139        }
140        Err(ClamberError::JwtMissingFieldError { field }) => {
141            println!("   → Token格式错误,缺少字段: {}", field);
142        }
143        Err(ClamberError::DeserializationError { details }) => {
144            println!("   → 数据格式错误: {}", details);
145        }
146        Err(e) => {
147            println!("   → 未知错误: {}", e);
148        }
149    }
150
151    // 模式2:错误传播
152    println!("\n   模式2:错误传播(? 操作符)");
153    let result = (|| -> Result<()> {
154        let user = User {
155            id: "test".to_string(),
156            username: "test".to_string(),
157            email: "test@example.com".to_string(),
158            role: "user".to_string(),
159        };
160        let token = generate_token(&user, JwtConfig::default())?;
161        let _decoded: User = verify_token(&token)?;
162        Ok(())
163    })();
164
165    match result {
166        Ok(()) => println!("   ✓ 操作序列成功完成"),
167        Err(e) => println!("   ✗ 操作序列失败: {}", e),
168    }
169
170    // 模式3:错误转换和上下文
171    println!("\n   模式3:错误上下文处理");
172    let result = (|| -> Result<String> {
173        let config = JwtConfig::new("test_secret", 1);
174        let manager = JwtManager::new(config);
175
176        let user = User {
177            id: "context_test".to_string(),
178            username: "context_user".to_string(),
179            email: "context@example.com".to_string(),
180            role: "user".to_string(),
181        };
182
183        manager.generate_token(&user)
184    })();
185
186    match result {
187        Ok(token) => println!("   ✓ 生成token成功: {}...", &token[..20]),
188        Err(e) => println!("   ✗ 生成token失败: {}", e),
189    }
190
191    println!("\n   ✓ 错误处理模式演示完成");
192}

Trait Implementations§

Source§

impl Clone for JwtConfig

Source§

fn clone(&self) -> JwtConfig

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for JwtConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for JwtConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more