How can I use $this->Auth->user() in middleware?

<?php
declare(strict_types=1);

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Cake\Auth;
/**
 * Admin middleware
 */
class AdminMiddleware implements MiddlewareInterface
{
    /**
     * Process method.
     *
     * @param \Psr\Http\Message\ServerRequestInterface $request The request.
     * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
     * @return \Psr\Http\Message\ResponseInterface A response.
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $this->Auth->user();
        return $handler->handle($request);
    }
}

here is the sample code

What version of CakePHP are you using? And it looks like you’re using the old, deprecated Auth component instead of the new plugins? Are you just getting started on this project and open to changing to the newer, better method, or is this a pre-existing thing that’s not ready for that change right now?

If you use the new Authentication Plugin you can access the currently logged in user via the request object like so:

$request->getAttribute('identity');

unless you changed the attribute name to something different.

This however requires, that your custom AdminMiddleware is added to the middleware queue AFTER the AuthenticationMiddleware.