auth-framework 0.4.2

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# Web Framework Integration Guide


This guide covers how to integrate auth-framework with popular Rust web frameworks.

## Actix-web Integration


Actix-web is a powerful, pragmatic, and extremely fast web framework for Rust.

### Setup


Add the actix-web feature to your `Cargo.toml`:

```toml
[dependencies]
auth-framework = { version = "0.1.0", features = ["actix-web"] }
actix-web = "4.0"
tokio = { version = "1.0", features = ["full"] }
```

### Basic Configuration


```rust
use actix_web::{web, App, HttpServer, Result, HttpResponse};
use auth_framework::{
    AuthFramework, InMemoryStorage,
    config::AuthConfig,
    integrations::actix_web::{AuthMiddleware, AuthenticatedUser, RequirePermission},
};

#[actix_web::main]

async fn main() -> std::io::Result<()> {
    // Initialize storage
    let storage = InMemoryStorage::new();
    
    // Create auth configuration
    let config = AuthConfig::builder()
        .jwt_secret("your-secret-key-here".to_string())
        .token_expiry(chrono::Duration::hours(24))
        .build();
    
    // Create auth framework instance
    let auth = AuthFramework::new(storage, config).await.unwrap();
    
    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(auth.clone()))
            .wrap(AuthMiddleware::new())
            // Public routes
            .route("/login", web::post().to(login_handler))
            .route("/register", web::post().to(register_handler))
            // Protected routes
            .service(
                web::scope("/api")
                    .route("/profile", web::get().to(get_profile))
                    .route("/admin", web::get().to(admin_only))
            )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

### Authentication Handlers


```rust
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]

struct LoginRequest {
    username: String,
    password: String,
}

#[derive(Serialize)]

struct LoginResponse {
    access_token: String,
    refresh_token: String,
    expires_in: i64,
}

async fn login_handler(
    auth: web::Data<AuthFramework<InMemoryStorage>>,
    req: web::Json<LoginRequest>,
) -> Result<HttpResponse> {
    match auth.authenticate(&req.username, &req.password).await {
        Ok(token) => {
            let response = LoginResponse {
                access_token: token.access_token,
                refresh_token: token.refresh_token.unwrap_or_default(),
                expires_in: token.expires_at.timestamp(),
            };
            Ok(HttpResponse::Ok().json(response))
        }
        Err(_) => Ok(HttpResponse::Unauthorized().json("Invalid credentials")),
    }
}

#[derive(Deserialize)]

struct RegisterRequest {
    username: String,
    password: String,
    email: String,
}

async fn register_handler(
    auth: web::Data<AuthFramework<InMemoryStorage>>,
    req: web::Json<RegisterRequest>,
) -> Result<HttpResponse> {
    match auth.register_user(&req.username, &req.password).await {
        Ok(credentials) => Ok(HttpResponse::Created().json("User created successfully")),
        Err(e) => Ok(HttpResponse::BadRequest().json(format!("Registration failed: {}", e))),
    }
}
```

### Protected Route Handlers


```rust
// Simple authenticated route
async fn get_profile(user: AuthenticatedUser) -> Result<HttpResponse> {
    let profile = serde_json::json!({
        "user_id": user.user_id,
        "permissions": user.permissions,
        "roles": user.roles,
    });
    Ok(HttpResponse::Ok().json(profile))
}

// Admin-only route using permission guard
async fn admin_only(
    user: AuthenticatedUser,
    _admin: RequirePermission<"admin">,
) -> Result<HttpResponse> {
    Ok(HttpResponse::Ok().json(format!("Welcome, admin {}!", user.user_id)))
}

// Role-based route
async fn moderator_panel(
    user: AuthenticatedUser,
    _mod: RequireRole<"moderator">,
) -> Result<HttpResponse> {
    Ok(HttpResponse::Ok().json("Moderator panel"))
}
```

### Custom Middleware Configuration


```rust
use auth_framework::integrations::actix_web::{AuthMiddleware, AuthConfig as ActixAuthConfig};

// Custom auth middleware configuration
let auth_config = ActixAuthConfig::builder()
    .skip_paths(vec!["/health", "/metrics", "/static"])
    .require_auth_header(true)
    .custom_header_name("X-Auth-Token")
    .build();

let auth_middleware = AuthMiddleware::with_config(auth_config);

App::new()
    .wrap(auth_middleware)
    // ... routes
```

### Error Handling


```rust
use actix_web::{middleware::ErrorHandlers, http::StatusCode};
use auth_framework::integrations::actix_web::AuthError;

fn create_app() -> App<
    impl actix_web::dev::ServiceFactory<
        actix_web::dev::ServiceRequest,
        Config = (),
        Response = actix_web::dev::ServiceResponse,
        Error = actix_web::Error,
        InitError = (),
    >,
> {
    App::new()
        .wrap(
            ErrorHandlers::new()
                .handler(StatusCode::UNAUTHORIZED, handle_auth_error)
                .handler(StatusCode::FORBIDDEN, handle_forbidden_error)
        )
        // ... rest of app
}

fn handle_auth_error<B>(res: actix_web::dev::ServiceResponse<B>) -> actix_web::Result<ErrorHandlerResponse<B>> {
    let response = HttpResponse::Unauthorized()
        .json(serde_json::json!({"error": "Authentication required"}));
    Ok(ErrorHandlerResponse::Response(res.into_response(response.into_body())))
}
```

## Warp Integration


Warp is a super-easy, composable, web server framework for building HTTP APIs.

### Setup


```toml
[dependencies]
auth-framework = { version = "0.1.0", features = ["warp"] }
warp = "0.3"
tokio = { version = "1.0", features = ["full"] }
```

### Basic Configuration


```rust
use warp::Filter;
use auth_framework::{
    AuthFramework, InMemoryStorage,
    config::AuthConfig,
    integrations::warp::{with_auth, require_permission, require_role},
};

#[tokio::main]

async fn main() {
    // Initialize auth framework
    let storage = InMemoryStorage::new();
    let config = AuthConfig::default();
    let auth = AuthFramework::new(storage, config).await.unwrap();
    
    // Create auth filter
    let auth_filter = with_auth(auth.clone());
    
    // Public routes
    let login = warp::path("login")
        .and(warp::post())
        .and(warp::body::json())
        .and(warp::any().map(move || auth.clone()))
        .and_then(login_handler);
    
    let register = warp::path("register")
        .and(warp::post())
        .and(warp::body::json())
        .and(warp::any().map(move || auth.clone()))
        .and_then(register_handler);
    
    // Protected routes
    let profile = warp::path("profile")
        .and(warp::get())
        .and(auth_filter.clone())
        .map(|user: AuthenticatedUser| {
            warp::reply::json(&serde_json::json!({
                "user_id": user.user_id,
                "permissions": user.permissions,
            }))
        });
    
    let admin = warp::path("admin")
        .and(warp::get())
        .and(auth_filter.clone())
        .and(require_permission("admin"))
        .map(|user: AuthenticatedUser| {
            format!("Welcome, admin {}!", user.user_id)
        });
    
    let moderator = warp::path("moderator")
        .and(warp::get())
        .and(auth_filter)
        .and(require_role("moderator"))
        .map(|user: AuthenticatedUser| {
            "Moderator panel"
        });
    
    let routes = login
        .or(register)
        .or(profile)
        .or(admin)
        .or(moderator)
        .with(warp::cors().allow_any_origin())
        .recover(handle_rejection);
    
    warp::serve(routes)
        .run(([127, 0, 0, 1], 3030))
        .await;
}
```

### Request Handlers


```rust
async fn login_handler(
    req: LoginRequest,
    auth: AuthFramework<InMemoryStorage>,
) -> Result<impl warp::Reply, warp::Rejection> {
    match auth.authenticate(&req.username, &req.password).await {
        Ok(token) => {
            let response = LoginResponse {
                access_token: token.access_token,
                refresh_token: token.refresh_token.unwrap_or_default(),
                expires_in: token.expires_at.timestamp(),
            };
            Ok(warp::reply::json(&response))
        }
        Err(_) => Err(warp::reject::custom(AuthenticationError)),
    }
}

// Custom rejection types
#[derive(Debug)]

struct AuthenticationError;
impl warp::reject::Reject for AuthenticationError {}

async fn handle_rejection(err: warp::Rejection) -> Result<impl warp::Reply, std::convert::Infallible> {
    if err.is_not_found() {
        Ok(warp::reply::with_status("Not Found", warp::http::StatusCode::NOT_FOUND))
    } else if let Some(_) = err.find::<AuthenticationError>() {
        Ok(warp::reply::with_status("Unauthorized", warp::http::StatusCode::UNAUTHORIZED))
    } else {
        Ok(warp::reply::with_status("Internal Server Error", warp::http::StatusCode::INTERNAL_SERVER_ERROR))
    }
}
```

## Rocket Integration


Rocket is a web framework for Rust that makes it simple to write fast, secure web applications.

### Setup


```toml
[dependencies]
auth-framework = { version = "0.1.0", features = ["rocket"] }
rocket = { version = "0.5", features = ["json"] }
tokio = { version = "1.0", features = ["full"] }
```

### Basic Configuration


```rust
use rocket::{get, post, launch, routes, serde::json::Json, State};
use auth_framework::{
    AuthFramework, InMemoryStorage,
    config::AuthConfig,
    integrations::rocket::{AuthenticatedUser, RequirePermission, RequireRole, AuthFairing},
};

#[post("/login", data = "<req>")]

async fn login(
    req: Json<LoginRequest>,
    auth: &State<AuthFramework<InMemoryStorage>>,
) -> Result<Json<LoginResponse>, rocket::http::Status> {
    match auth.authenticate(&req.username, &req.password).await {
        Ok(token) => {
            let response = LoginResponse {
                access_token: token.access_token,
                refresh_token: token.refresh_token.unwrap_or_default(),
                expires_in: token.expires_at.timestamp(),
            };
            Ok(Json(response))
        }
        Err(_) => Err(rocket::http::Status::Unauthorized),
    }
}

#[get("/profile")]

fn get_profile(user: AuthenticatedUser) -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "user_id": user.user_id,
        "permissions": user.permissions,
        "roles": user.roles,
    }))
}

#[get("/admin")]

fn admin_only(_user: AuthenticatedUser, _admin: RequirePermission<"admin">) -> &'static str {
    "Admin panel"
}

#[get("/moderator")]

fn moderator_only(_user: AuthenticatedUser, _mod: RequireRole<"moderator">) -> &'static str {
    "Moderator panel"
}

#[launch]

async fn rocket() -> _ {
    let storage = InMemoryStorage::new();
    let config = AuthConfig::default();
    let auth = AuthFramework::new(storage, config).await.unwrap();
    
    rocket::build()
        .manage(auth)
        .attach(AuthFairing::default())
        .mount("/", routes![login, get_profile, admin_only, moderator_only])
}
```

### Custom Request Guards


```rust
use rocket::{Request, request::{self, FromRequest}};

// Custom request guard for specific permission levels
pub struct RequireAdminOrModerator;

#[rocket::async_trait]

impl<'r> FromRequest<'r> for RequireAdminOrModerator {
    type Error = ();

    async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
        let user = match AuthenticatedUser::from_request(req).await {
            request::Outcome::Success(user) => user,
            request::Outcome::Failure((status, _)) => return request::Outcome::Failure((status, ())),
            request::Outcome::Forward(_) => return request::Outcome::Forward(()),
        };

        if user.has_permission("admin") || user.has_role("moderator") {
            request::Outcome::Success(RequireAdminOrModerator)
        } else {
            request::Outcome::Failure((rocket::http::Status::Forbidden, ()))
        }
    }
}

#[get("/admin-or-mod")]

fn admin_or_mod_handler(
    _user: AuthenticatedUser,
    _guard: RequireAdminOrModerator,
) -> &'static str {
    "Admin or Moderator access"
}
```

## Common Patterns


### CORS Configuration


```rust
// Actix-web CORS
use actix_cors::Cors;

App::new()
    .wrap(
        Cors::default()
            .allowed_origin("http://localhost:3000")
            .allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
            .allowed_headers(vec!["Authorization", "Content-Type"])
            .max_age(3600)
    )

// Warp CORS
let cors = warp::cors()
    .allow_origin("http://localhost:3000")
    .allow_headers(vec!["authorization", "content-type"])
    .allow_methods(vec!["GET", "POST", "PUT", "DELETE"]);

routes.with(cors)

// Rocket CORS (using rocket_cors crate)
use rocket_cors::{AllowedOrigins, CorsOptions};

let cors = CorsOptions::default()
    .allowed_origins(AllowedOrigins::some_exact(&["http://localhost:3000"]))
    .allowed_methods(vec![Method::Get, Method::Post, Method::Put, Method::Delete].into_iter().map(From::from).collect())
    .allow_credentials(true);

rocket::build().attach(cors.to_cors().unwrap())
```

### Rate Limiting


```rust
// Custom rate limiting middleware for Actix-web
use actix_web::dev::{ServiceRequest, ServiceResponse};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

struct RateLimiter {
    requests: Arc<Mutex<HashMap<String, Vec<Instant>>>>,
    max_requests: usize,
    window: Duration,
}

impl RateLimiter {
    fn new(max_requests: usize, window: Duration) -> Self {
        Self {
            requests: Arc::new(Mutex::new(HashMap::new())),
            max_requests,
            window,
        }
    }

    fn is_allowed(&self, client_ip: &str) -> bool {
        let mut requests = self.requests.lock().unwrap();
        let now = Instant::now();
        
        let client_requests = requests.entry(client_ip.to_string()).or_insert_with(Vec::new);
        
        // Remove old requests
        client_requests.retain(|&time| now.duration_since(time) < self.window);
        
        if client_requests.len() < self.max_requests {
            client_requests.push(now);
            true
        } else {
            false
        }
    }
}
```

### Session Management


```rust
// Session-based authentication alongside JWT
use auth_framework::storage::SessionData;

async fn create_session_handler(
    auth: web::Data<AuthFramework<InMemoryStorage>>,
    user: AuthenticatedUser,
) -> Result<HttpResponse> {
    let session_data = SessionData {
        user_id: user.user_id.clone(),
        data: serde_json::json!({"last_login": chrono::Utc::now()}),
        created_at: chrono::Utc::now(),
        last_accessed: chrono::Utc::now(),
    };
    
    let session_id = uuid::Uuid::new_v4().to_string();
    auth.storage.store_session(&session_id, &session_data).await.unwrap();
    
    Ok(HttpResponse::Ok().json(serde_json::json!({"session_id": session_id})))
}
```

### Custom Claims


```rust
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]

struct CustomClaims {
    sub: String,
    exp: i64,
    permissions: Vec<String>,
    roles: Vec<String>,
    custom_field: String,
}

// Use custom claims in your handlers
async fn custom_protected_handler(
    req: HttpRequest,
    auth: web::Data<AuthFramework<InMemoryStorage>>,
) -> Result<HttpResponse> {
    let token = extract_token_from_request(&req)?;
    let claims: CustomClaims = auth.verify_custom_token(&token).await?;
    
    if claims.custom_field == "special_value" {
        Ok(HttpResponse::Ok().json("Special access granted"))
    } else {
        Ok(HttpResponse::Forbidden().json("Special access required"))
    }
}
```

## Testing Web Framework Integrations


```rust
#[cfg(test)]

mod tests {
    use super::*;
    use actix_web::{test, App};
    
    #[actix_web::test]
    async fn test_protected_route() {
        let storage = InMemoryStorage::new();
        let config = AuthConfig::default();
        let auth = AuthFramework::new(storage, config).await.unwrap();
        
        // Create test user
        auth.register_user("testuser", "password").await.unwrap();
        let token = auth.authenticate("testuser", "password").await.unwrap();
        
        let app = test::init_service(
            App::new()
                .app_data(web::Data::new(auth))
                .wrap(AuthMiddleware::new())
                .route("/protected", web::get().to(get_profile))
        ).await;
        
        let req = test::TestRequest::get()
            .uri("/protected")
            .insert_header(("Authorization", format!("Bearer {}", token.access_token)))
            .to_request();
        
        let resp = test::call_service(&app, req).await;
        assert!(resp.status().is_success());
    }
}
```

This guide covers the essential patterns for integrating auth-framework with popular Rust web frameworks. Each framework has its own idioms and patterns, but the auth-framework provides consistent interfaces that work naturally with each one.