# API with wrong credentials redirects to html login form

**URL:** <https://discourse.cakephp.org/t/api-with-wrong-credentials-redirects-to-html-login-form/9913>\
**Category:** Plugins\
**Tags:** help\
**Created:** [November 18, 2021, 9:36pm UTC](https://discourse.cakephp.org/t/api-with-wrong-credentials-redirects-to-html-login-form/9913 "2021-11-18T21:36:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![atlet](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/atlet/32/129_2.png) [@atlet](https://discourse.cakephp.org/u/atlet)\
**Post date:** [November 18, 2021, 9:36pm UTC](https://discourse.cakephp.org/t/api-with-wrong-credentials-redirects-to-html-login-form/9913/1 "2021-11-18T21:36:45Z")

</div>

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](https://book.cakephp.org/4/en/development/rest.html)

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

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

```

This is config in users.php:

```auto
'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.

 ![image](https://canada1.discourse-cdn.com/flex029/uploads/cakephp/original/2X/c/c700eeb2be2a7bece347f9400e96e0ff9dbb9b5a.png)

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

Tnx

---

<div class="post-metadata">

**Author:** ![atlet](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/atlet/32/129_2.png) [@atlet](https://discourse.cakephp.org/u/atlet)\
**Post date:** [November 24, 2021, 7:52am UTC](https://discourse.cakephp.org/t/api-with-wrong-credentials-redirects-to-html-login-form/9913/2 "2021-11-24T07:52:03Z")

</div>

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

in config/users.php I added this line:

```auto
'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.
