Api's getting response in html form with POST request

Hi… Developer I need help I am building Api’s for my web application but i am stuck in the response. I am using Authentication and Authorization plugin and these are configure in the application.php file. It work fine for web based form but when i send request from Post-Man with POST method I am getting here Html template file in response but i when i send request with GET Method then i get result, So please help how to allow Post request fetch data but not redirect me to login response in Api’s . let me show :-
You can see with Post request i am getting from in respons



above image you can see with get request i am getting result… so please suggest me how can tackle this issue.

//application.php
->add(new AuthenticationMiddleware($this))

        // Add authorization **after** authentication
        ->add(new AuthorizationMiddleware($this, [
            'unauthorizedHandler' => [
                'className' => CheckAccess::class,
                'url' => [
                    'controller' => 'Accounts',
                    'action' => 'login'
                ],
                'queryParam' => 'redirect',
                'exceptions' => [
                    ForbiddenException::class
                ]
            ]
        ]))

        ->add(new RequestAuthorizationMiddleware())

$service = new AuthenticationService();
$fields = [
IdentifierInterface::CREDENTIAL_USERNAME => ‘email’,
IdentifierInterface::CREDENTIAL_PASSWORD => ‘password’
];
$service->setConfig([
‘unauthenticatedRedirect’ => Router::url([‘prefix’ => false, ‘plugin’ => null, ‘controller’ => ‘Accounts’, ‘action’ => ‘login’]),
‘queryParam’ => ‘redirect’,
]);
if (strpos($request->getPath(), ‘/api’) === 0) {

        $service->loadIdentifier('Authentication.JwtSubject');


        $service->loadAuthenticator('Authentication.Jwt', [
            'secretKey' => file_get_contents(CONFIG . 'jwt.pem'),
            'algorithm' => 'RS256',
            'returnPayload' => false
        ]);

        return $service;

Blockquote

Ok So I am here @daryl . So you are using Authentication and Authorization plugin and do some some configuration in middleware side right. Right now whats going on man when you send request from Post-man with POST method then Authorization plugin execute silently and it restrict POST request, not even POST request it has been restricting the PUT,DELETE and HEAD Request too…Except GET Request. The Solution is that here you have to set this $this->Authorization->skipAuthorization(); method into particular method or you set it into beforeFilter method.

    $this->Authentication->addUnauthenticatedActions(['index', 'view']);
    if (in_array($this->request->getParam('action'), ['index', 'view'])) {
        $this->Authorization->skipAuthorization();
    }

I hope it will help you and fix your issue

1 Like

Yo!! Man its working, thanks @shaan007 I tested this code and it really work for me. thank again @shaan007