Middleware redirect to if user have not permissions

I just create a class and include it into middleware authorization middleware

type or paste code heredeclare(strict_types=1);

namespace App\Middleware\UnauthorizedHandler;

use Cake\Http\Response;
use Authorization\Exception\Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Authorization\Middleware\UnauthorizedHandler\CakeRedirectHandler;
use Cake\Routing\Router;

class CheckRedirect extends CakeRedirectHandler

     * {@inheritDoc}
     * Return a response with a location header set if an exception matches.
    public function handle(
        Exception $exception,
        ServerRequestInterface $request,
        array $options = []
    ): ResponseInterface {
        $options += $this->defaultOptions;

        if (!$this->checkException($exception, $options['exceptions'])) {
            throw $exception;

         * @var \Cake\Http\ServerRequest $request

        if ($request->getAttribute('identity') === null) {
            // stop appending ?redirect=/controller/action
            $options['queryParam'] = null;

            // if not logged in redirect to /users/login
            $url = $this->getUrl($request, $options);

            $flashMessage = "You need to be logged in to access that location";
        } else {
            $url = $request->referer(false) ?? Router::url($options['noRefererRedirect']);

            $flashMessage = "You don't have access to {$request->getPath()}";


        return (new Response())
            ->withHeader('Location', $url);

but this call does not redirect to sepcific page but just throw error but as you seen in my above code i just redirect user to specific page but this call does not work.

i just want to redirect user to specific page with flash message but that all does not work… can tell me what i am doing wrong here

There’s a ForbiddenException in the core as well as in the authorization plugin, so first things first, check if the use statement for the ForbiddenException class you’re referencing in Application.php is actually pointing to Authorization\Exception\ForbiddenException instead of possibly Cake\Http\Exception\ForbiddenException.

I need solution @ndm . what should i need to change in code and how to user to redirect to back previous location with flash message if user have not permissions. I already built system role permission but now i just want to redirect user if not permission or authorized to access action. as you can seen above error throw identity is not authorized so my role permission working fine but i want to redirect user back user page instead you that error page, I want to do that all with middleware not from controller side… because my application is large so i do not want to write again and again same code in controller so better way to it handle via middleware. please helping me if you have any idea with code example