#middleware #cognito #actix-web #actix

actix-web-middleware-cognito

Middleware for actix-web that helps you validate Cognito tokens

5 releases (3 breaking)

Uses new Rust 2021

0.4.0-beta.19 Jan 7, 2022
0.4.0-beta.5 Jun 5, 2021
0.3.0 Sep 25, 2020
0.2.0 Aug 4, 2020
0.1.0 Aug 3, 2020

#101 in HTTP server

Download history 1/week @ 2022-03-02 21/week @ 2022-03-16 22/week @ 2022-03-23 1/week @ 2022-04-06 7/week @ 2022-04-20 16/week @ 2022-04-27 36/week @ 2022-05-04 75/week @ 2022-05-11 22/week @ 2022-05-18 23/week @ 2022-05-25 41/week @ 2022-06-01 20/week @ 2022-06-08 2/week @ 2022-06-15

86 downloads per month

MIT license

19KB
300 lines

actix-web-middleware-cognito

ActionsStatus Crates.io API

Middleware for actix-web that helps you validate Cognito tokens.

Cognito validator

Before setting up the middleware we have to create a CognitoValidator that will be built by receiving some variables from the environment:

  • COGNITO_REGION: The region of the Cognito pool.
  • COGNITO_POOLID: The Cognito pool id.
  • COGNITO_CLIENTID: The client id of your app.
  • COGNITO_ENABLED (optional): if not present or 0 no validation will be done.
  • COGNITO_VERIFY_ACCESSTOKEN (optional): if not present or 0 idToken will be validated. If present, the accessToken will be validated instead.

Usage

Setting up the middleware:

// builidng the validator in order to be shared between all threads.
let cognito_validator =
    Arc::new(CognitoValidator::create().expect("Cognito configuration error"));

HttpServer::new(move || {
    // cognito middleware
    let cognito = Cognito::new(cognito_validator.clone());

    // set up the app
    App::new()
        .wrap(cognito)
        .route("/", web::get().to(index))
})
.bind(format!("0.0.0.0:{}", PORT))
.unwrap_or_else(|_| panic!("🔥 Couldn't start the server at port {}", PORT))
.run()
.await

Extracting the token from the request

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.

async fn index(auth: CognitoInfo) -> impl Responder {
    let msg = format!(
        "User with id {} made this call with token {}",
        auth.user.unwrap(),
        auth.token.unwrap()
    );
    HttpResponse::Ok().body(msg)
}

Example

You can check the example in the repo or run it: cargo run --example main.

Dependencies

~25–34MB
~789K SLoC