actix_web_middleware_cognito/
lib.rs

1//! Middleware for [actix-web](https://github.com/actix/actix-web) that helps you validate Cognito tokens.
2//!
3//! ## Cognito validator
4//!
5//! Before setting up the middleware we have to create a `CognitoValidator` that will be built by receiving some vari ables from the environment:
6//!
7//! - **COGNITO_REGION**: The region of the Cognito pool.
8//! - **COGNITO_POOLID**: The Cognito pool id.
9//! - **COGNITO_CLIENTID**: The client id of your app.
10//! - **COGNITO_ENABLED** (optional): if not present or 0 no validation will be done.
11//! - **COGNITO_VERIFY_ACCESSTOKEN** (optional): if not present or 0 idToken will be validated. If present, the accessToken will be validated instead.
12//!
13//! ## Usage
14//!
15//! Setting up the middleware:
16//!
17//! ```rust,no_run
18//! # use actix_web::{web, App, HttpServer};
19//! # use actix_web_middleware_cognito::{Cognito, CognitoValidator};
20//! # use std::sync::Arc;
21//! # const PORT: &str = "3000";
22//! # async fn index() -> &'static str {
23//! #   "Hello world"
24//! # }
25//! # #[actix_rt::main]
26//! # async fn main() -> std::io::Result<()> {
27//! // builidng the validator in order to be shared between all threads.
28//! let cognito_validator =
29//!     Arc::new(CognitoValidator::create().expect("Error configuring the Cognito validator"));
30//!
31//! HttpServer::new(move || {
32//!     // cognito middleware
33//!     let cognito = Cognito::new(cognito_validator.clone());
34//!
35//!     // set up the app
36//!     App::new()
37//!         .wrap(cognito)
38//!         .route("/", web::get().to(index))
39//! })
40//! .bind(format!("0.0.0.0:{}", PORT))
41//! .unwrap_or_else(|_| panic!("🔥 Couldn't start the server at port {}", PORT))
42//! .run()
43//! .await
44//! # }
45//! ```
46//!
47//! ## Extracting the token from the request
48//!
49//! The library provides a `CognitoInfo` extractor for you to get information about the Cognito token. If the token is invalid or you disable the middleware (by omitting the `COGNITO_ENABLED` environment variable) you will always get a disabled `CognitoInfo`, i.e. a `CognitoInfo` with no `token`.
50//!
51//! ```rust,no_run
52//! # use actix_web::{Responder, HttpResponse};
53//! # use actix_web_middleware_cognito::CognitoInfo;
54//! async fn index(auth: CognitoInfo) -> impl Responder {
55//!     let msg = format!(
56//!         "User with id {} made this call with token {}",
57//!         auth.user.unwrap(),
58//!         auth.token.unwrap()
59//!     );
60//!     HttpResponse::Ok().body(msg)
61//! }
62//! ```
63
64mod extractor;
65mod middleware;
66mod validator;
67
68pub use extractor::CognitoInfo;
69pub use middleware::Cognito;
70pub use validator::CognitoValidator;