4 个版本 (1 个稳定版)

1.0.0 2023年11月19日
0.2.1 2023年9月24日
0.2.0 2023年6月29日
0.1.0 2023年6月22日

#519 in HTTP 服务器

Download history 3/week @ 2024-03-13 3/week @ 2024-03-27 2/week @ 2024-04-03 1/week @ 2024-04-10 16/week @ 2024-04-17 18/week @ 2024-04-24 8/week @ 2024-05-01 3/week @ 2024-05-08 17/week @ 2024-05-15 58/week @ 2024-05-22 73/week @ 2024-05-29 116/week @ 2024-06-05 115/week @ 2024-06-12 63/week @ 2024-06-19 71/week @ 2024-06-26

每月下载量 372

MIT/Apache

19KB
372 代码行

actix-web 的 JWT 验证中间件

此中间件使用 JWKS 验证 JWT。

用法

cargo add actix-web-jwt

示例

use std::sync::Arc;

use actix_web::HttpServer;
use actix_web_jwt::{Jwt, CertInvoker};
use tokio_cron_scheduler::{JobScheduler, Job};

#[tokio::main]
async fn main() -> std::io::Result<()> {
    
    let invoker = CertInvoker::from(String::from("https://www.googleapis.com/oauth2/v3/certs"));

    let arc_jwt = Arc::new(invoker);
    let cloned_arc_jwt = Arc::clone(&arc_jwt);

    let sched = JobScheduler::new().await.unwrap();
    
    let job = Job::new_async("1/10 * * * * *", move |_uuid, mut _l| {
        let cloned_arc_jwt = Arc::clone(&cloned_arc_jwt);
        Box::pin(async move {
            cloned_arc_jwt.get_cert().await;
        })
    })
    .unwrap();
    sched.add(job).await.unwrap();
    let scheduler = sched.start();
    
    let server = HttpServer::new(move || {
        actix_web::App::new()
            .wrap(Jwt::from(Arc::clone(&arc_jwt), Some(Arc::new(Validate{}))))
    })
    .bind("127.0.0.1:8080")
    .unwrap()
    .run();

    let _ = futures::future::join(scheduler, server).await;
    Ok(())
}

struct Validate;

impl JWTValidator for Validate {
    
    fn validate(&self,toke_data:TokenData<Claims>) -> Result<(), JWTResponseError> {
        println!("validate token data: {:?}", toke_data);
        if let Some(aud) = toke_data.claims.aud {
            if aud != "1234567890" {
                return Err(JWTResponseError::toke_validation_error(StatusCode::UNAUTHORIZED, "aud error".to_string()));
            }
        }
        Ok(())
    }
}

依赖项

~15–29MB
~528K SLoC