Actix-web token validation in middleware

Hi all,

I'm starting working with actix-web v2.0 for publishing a small web app at work.

One of my needs is to authenticate a session token received from another service.

I thought I can do that with a middleware, but I have an issue recovering the Identity.

Here is the server code:

let server = HttpServer::new(move || {
             .data(AppOptions {
                 root: root_folder.clone(),
             .wrap(Logger::new("%a %{User-Agent}i"))
             .route("/api", web::to(ws_proxy))

I set a CookieIdentityPolicy before my middleware that is authorization::Authorization.

I can access to the Identity from my service static_site without a problem.

From the middleware I just can't:

impl<S, B> Service for AuthorizationService<S>
     S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
     S::Future: 'static,
     B: 'static,
     type Request = ServiceRequest;
     type Response = ServiceResponse<B>;
     type Error = Error;
     type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

     fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {

     fn call(&mut self, req: ServiceRequest) -> Self::Future {
         println!("Hi from start. You requested: {:?}", req.path());

         if req.get_identity().is_none() {
             // Should never reach this branch
             println!("Error not identity found");
             return Box::pin(async { Err(actix_web::error::ErrorUnauthorized("Unauthorized")) });
         } else {
             // Here I should check the identity first
             Box::pin( )

At the time being the code is just for understanding how a middleware works, the line with req.get_identity() always return a None, and that should be incorrect.

On documentations looks like it should be fine:

Not sure what I'm doing wrong, any help would be appreciated.


I don't think this is documented anywhere yet, but use RequestIdentity for this:

use actix_identity::RequestIdentity;

fn call(&mut self, req: ServiceRequest) -> Self::Future {
    let identity = RequestIdentity::get_identity(&req);

@ddimaria thanks for reply, I changed the code as you suggested, but still the identity is None.

Not sure what I'm doing wrong here, the identity session middleware is declared before my middleware, and that, according to the documentation, should be ok to have it defined.

I also made an example with the UserSession middleware and it didn't work. Looks like I cannot read the cookie from the request header. :frowning:

I found a package that can be helpfull to understand this part. I'll have a look on this to see if that works and how it's different from my example.

I'll be back after that.


The actix-web-httpauth works, but just use the header extractors for Basic and Bearer.

That works in my example too.

It doesn't work with cookie.

I'll post my relevant auth code sections:

The server code:

let mut server = HttpServer::new(move || {


pub fn get_identity_service() -> IdentityService<CookieIdentityPolicy> {

For middleware, I have that in within my routes:

pub fn routes(cfg: &mut web::ServiceConfig) {
        // Healthcheck
        .route("/health", web::get().to(get_health))
        // /api/v1 routes
                // Lock down routes with AUTH Middleware

That make sense, didn't have a chance to test it today but I will try it tomorrow.

Thanks a lot for the help @ddimaria, I didn't understood that middleware can be placed inside a server, my bad.

But that is, when I modify my code according to your suggestions, I can get the cookie session in my middleware!

1 Like