actix_jwt/lib.rs
1//! Full-featured JWT authentication middleware for [actix-web].
2//!
3//! This crate is a Rust port of
4//! [`echo-jwt`](https://github.com/LdDl/echo-jwt) (Go implementation, itself a port of
5//! [`gin-jwt`](https://github.com/appleboy/gin-jwt) to the Echo framework).
6//! It goes far beyond simple token validation - it provides login, logout and
7//! refresh handlers, refresh-token rotation with a pluggable store, cookie
8//! management, RSA / HMAC signing, RBAC authorizer callback and more.
9//!
10//! # Feature flags
11//!
12//! | Flag | Default | Description |
13//! |------|---------|-------------|
14//! | `redis-store` | off | Enables `RedisRefreshTokenStore` backed by the [`redis`](https://crates.io/crates/redis) crate. |
15//!
16//! # Quick start
17//!
18//! ```rust,no_run
19//! use std::sync::Arc;
20//!
21//! use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};
22//! use actix_jwt::{ActixJwtMiddleware, extract_claims};
23//!
24//! #[actix_web::main]
25//! async fn main() -> std::io::Result<()> {
26//! let mut jwt = ActixJwtMiddleware::new();
27//! jwt.key = b"my-secret-key".to_vec();
28//! jwt.authenticator = Some(Arc::new(|_req, body| {
29//! #[derive(serde::Deserialize)]
30//! struct Login { username: String, password: String }
31//! let result = (|| {
32//! let creds: Login = serde_json::from_slice(body)
33//! .map_err(|_| actix_jwt::JwtError::MissingLoginValues)?;
34//! if creds.username == "admin" && creds.password == "admin" {
35//! Ok(serde_json::json!({"username": creds.username}))
36//! } else {
37//! Err(actix_jwt::JwtError::FailedAuthentication)
38//! }
39//! })();
40//! Box::pin(async move { result })
41//! }));
42//! jwt.init().expect("JWT middleware init");
43//!
44//! let jwt = Arc::new(jwt);
45//! let jwt_data = web::Data::new(jwt.clone());
46//!
47//! HttpServer::new(move || {
48//! App::new()
49//! .app_data(jwt_data.clone())
50//! .route("/login", web::post().to({
51//! let j = jwt.clone();
52//! move |req: HttpRequest, body: web::Bytes| {
53//! let j = j.clone();
54//! async move { j.login_handler(&req, &body).await }
55//! }
56//! }))
57//! .service(
58//! web::scope("/api")
59//! .wrap(jwt.middleware())
60//! .route("/hello", web::get().to(|req: HttpRequest| async move {
61//! let claims = extract_claims(&req);
62//! HttpResponse::Ok().json(claims)
63//! })),
64//! )
65//! })
66//! .bind("127.0.0.1:8080")?
67//! .run()
68//! .await
69//! }
70//! ```
71
72pub mod core;
73pub mod errors;
74pub mod middleware;
75pub mod store;
76
77pub use core::{RefreshTokenData, Token, TokenStore};
78pub use errors::JwtError;
79pub use middleware::{
80 ActixJwtMiddleware, CookieConfig, JwtAuth, JwtIdentity, JwtPayload, JwtTokenString,
81 extract_claims, get_identity, get_token,
82};
83pub use store::{InMemoryRefreshTokenStore, default_store, new_memory_store};