欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Rust : Json Web Token

程序员文章站 2024-02-04 08:09:04
...

JWT的原理
https://zhuanlan.zhihu.com/p/27370773

代码:
来源:https://github.com/Keats/jsonwebtoken

use std::{thread, time};
extern crate jsonwebtoken as jwt;
#[macro_use]
extern crate serde_derive;

use jwt::errors::ErrorKind;
use jwt::{decode, encode, Algorithm, Header, Validation};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String,
    company: String,
    exp: usize,
}

fn main() {
    let sleep_seconds = time::Duration::from_secs(1000);
    let my_claims = Claims {
        sub: "[email protected]".to_owned(),
        company: "ACME".to_owned(),
        exp: 10000000000,
    };
    let key = "secret";

    let mut header = Header::default();
    header.kid = Some("signing_key".to_owned());
    header.alg = Algorithm::HS512;

    let token = match encode(&header, &my_claims, key.as_ref()) {
        Ok(t) => t,
        Err(_) => panic!(), // in practice you would return the error
    };
    println!("token:{:?}", token);

    let token_data =
        match decode::<Claims>(&token, key.as_ref(), &Validation::new(Algorithm::HS512)) {
            Ok(c) => c,
            Err(err) => match *err.kind() {
                ErrorKind::InvalidToken => panic!(), // Example on how to handle a specific error
                _ => panic!(),
            },
        };
    println!("claims:{:?}", token_data.claims);
    println!("header:{:?}", token_data.header);
    println!("jwt, i am learning it!");
    thread::sleep(sleep_seconds);
}