cakephp 3.8.13 handle unauthorized request, response in JSON

216 Views Asked by At

I have implemented https://github.com/ADmad/cakephp-jwt-auth in my CakePHP application. My problem is whenever there is an unauthorized request it responds with HTML.

    <html>
        <head>
            <meta charset="utf-8"/>
            <title>
            CakePHP: the rapid development php framework:
            Error   </title>
            <link href="/favicon.ico" type="image/x-icon" rel="icon"/>
            <link href="/favicon.ico" type="image/x-icon" rel="shortcut icon"/>
            <link rel="stylesheet" href="/css/cake.generic.css"/>
        </head>
        <body>
            <div id="container">
                <div id="header">
                    <h1>
                        <a href="https://cakephp.org">CakePHP: the rapid development php framework</a>
                    </h1>
                </div>
                <div id="content">
                    <h2>Unauthorized</h2>
                    <p class="error">
                        <strong>Error: </strong>
                        An Internal Error Has Occurred.
                    </p>
                </div>
              </div>
          </body>
    </html>

But according to this tutorial https://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/, it will respond with JSON. An example response from the tutorial is

{
    "success": false,
    "data": {
        "message": "You are not authorized to access that location.",
        "url": "\/api\/cocktails.json",
        "code": 401
    }
}

This is my router

Router::prefix('api', function ($routes) {
    $routes->extensions(['json', 'xml']);
    Router::connect('/api/check', ['_method' => 'GET','controller' => 'EmailNotification', 'action' => 'check', 'prefix' => 'api']);
    $routes->fallbacks('DashedRoute');
});

How can I handle this? I want the unauthorised response in JSON. Thank you.

1

There are 1 best solutions below

0
On BEST ANSWER

can you try sending your http request with Accept:application/json header