API with wrong credentials redirects to html login form

I created a new application with CakePHP 4. For authentication I used CakeDC/users plugin. It’s working fine. I can login to application.

I also added REST API following this instructions: REST - 4.x

For authentication to API I use Token based and it’s working fine. For API I created a new prefix:

$routes->prefix('Api', function (RouteBuilder $routes) {
    $routes->setExtensions(['json']);
    $routes->fallbacks(DashedRoute::class);
});

This is config in users.php:

'Auth.Authenticators.Token' => [
        'className' => 'Authentication.Token',
        'skipTwoFactorVerify' => true,
        'header' => 'authorization',
        'queryParam' => 'api_token',
        'tokenPrefix' => 'Token',        
        'unauthenticatedRedirect' => null
    ],

Problem happen when I enter wrong Token. API returns HTML login form. I would like that returns 401.

Is there any good tutorial or any hint, how can solve this issue?

Tnx

I created custom unauthorizedHandler class and it’s working fine.

in config/users.php I added this line:

'Auth.AuthorizationMiddleware.unauthorizedHandler.className' => 'CustomRedirect',

And created a new file CustomRedirectHandler.php in src/Middleware/UnauthorizedHandler directory.

Also I was missing the accept: application/json header.