App creation

Insert the following code into a closure of the server::new function call:

let app = App::with_state(State::default())
.middleware(middleware::Logger::default())
.middleware(IdentityService::new(
CookieIdentityPolicy::new(&[0; 32])
.name("auth-example")
.secure(false),
))
.middleware(Counter);

The App struct contains information about the state, middleware, and the scopes of routes. To set shared state to our application, we use the with_state method to construct the App instance. We create a default instance of the State struct, which is declared as follows:

#[derive(Default)]
struct State(RefCell<i64>);

State contains a cell with an i64 value to count all requests. By default, it is created with a 0 value.

After this, we use the middleware method of App to set the three following middlewares:

  • actix_web::middleware::Logger is a logger that uses the log crate to log request and responses
  • actix_web::middleware::identity::IdentityService helps to identity requests using an identity backend that implements the IdentityPolicy trait
  • Counter is a piece of middleware that we will create in the following Middleware section, and uses State to count the total quantity of requests

For our IdentityPolicy backend, we use CookieIdentityPolicy from the same identity submodule where IdentityService lives. CookieIdentityPolicy expects a key with at least 32 bytes. When an instance of an identity policy for cookies has been created, we can use methods like path, name, and domain to set specific cookies parameters. We also allow the sending of cookies with insecure connections by using the secure method with a false value.

There are two special parameters of cookies you should know about: Secure and HttpOnly. The first requires secure HTTPS connection to send cookies. If you run a service for testing and use plain HTTP to connect to it, then the CookieIdentityPolicy won't work. HttpOnly parameters don't allow the use of cookies from JavaScript. CookieIdentityPolicy sets this parameter to true and you can't override this behavior.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.229