Search code examples
phpcodeignitercodeigniter-4

RestFul API For Delete And Update Get 403 Forbidden Codeigniter 4


Remember this is codeigniter 4.

I need help in here. I am learning to implement about the RestFul API in codeigniter 4. Below is my detail code.

Routes :

$routes->resource('ApiManageMaintenance', ['controller' =>'App\Controllers\ApiData\ApiManageMaintenance']); // get, put, create, delete

ApiManageMaintenance.php :

<?php
 
namespace App\Controllers\ApiData;
use App\Controllers\BaseController;
use CodeIgniter\RESTful\ResourceController;


class ApiManageMaintenance extends ResourceController
{    

    function __construct()
    {       

        $model = new Dennis_setting_model();    
            

    }
    

    // equal to get    
    public function index()
    {          
        $Medoo = new \App\Models\Dennis_medoo_model();      
        $result = $Medoo->SelectAllMaintenance();   

        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Pull Data Successfull',
            'data'     => $result
        ];            
        
        return json_encode($response); 
        
    }
    
        
    // equal to post
    public function create() {
        $version = $this->request->getVar('version');
        $reason = $this->request->getVar('reason');     

        if ($version == "" || $reason == "") {
            $response = [
                'status'   => 102,
                'error'    => 'Data Error',
                'messages' => 'Data Not Valid',
                'data' => null 
            ];         
            
            return json_encode($response);            
        }

        $array = array ('version' => $version,
                  'reason' => $reason
        );

        $Medoo = new \App\Models\Dennis_medoo_model();      
        $Medoo->InsertNewMaintenance($array);
        
        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Create New Maintenance Successfull',
            'data'     => null
        ];            
        
        return json_encode($response);        

    }

    // equal to get
    public function show($id = null) {

        $Medoo = new \App\Models\Dennis_medoo_model();      
        $result = $Medoo->SelectAllMaintenance();   

        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Pull Data Successfull',
            'data'     => $result
        ];            
        
        return json_encode($response); 
    }

    // equal to put    
    public function update($id = null) {
        $data = $this->request->getRawInput();
        $data['id'] = $id;

        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Update Data Successfull',
            'data'     => null
        ];            
        
        return json_encode($response);
    }
    

    // equal to delete
    public function delete($id = null) {        
        $Medoo = new \App\Models\Dennis_medoo_model();
        $Medoo->DeleteMaintenance($id);
        $response = [
            'status'   => 200,
            'error'    => null,
            'messages' => 'Delete Data Successfull',
            'data'     => null
        ];            
        
        return json_encode($response);
        
    }

}

Config Filter.php

<?php namespace Config;

use CodeIgniter\Config\BaseConfig;

class Filters extends BaseConfig
{
    // Makes reading things below nicer,
    // and simpler to change out script that's used.
    public $aliases = [
        'csrf'     => \CodeIgniter\Filters\CSRF::class,
        'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
        'honeypot' => \CodeIgniter\Filters\Honeypot::class,
        'auth' => \App\Filters\Auth::class,
        'authaccess' => \App\Filters\AuthAccess::class
    ];

    // Always applied before every request
    public $globals = [
        'before' => [
            //'honeypot'
            'csrf' => ['except' => [
                    'api/ApiManageMaintenance/delete'
                ]
            ]           
        ],
        'after'  => [
            'toolbar',
            //'honeypot'
        ],
    ];


    // Works on all of a particular HTTP method
    // (GET, POST, etc) as BEFORE filters only
    //     like: 'post' => ['CSRF', 'throttle'],
    public $methods = [
        
    ];

    // List filter aliases and any before/after uri patterns
    // that they should run on, like:
    //    'isLoggedIn' => ['before' => ['account/*', 'profiles/*']],
    public $filters = [];
}

Note : I am using thirdparty database library => Medoo, So just ignore it. I am not using the build in framework database query in codeigniter for some reason because Medoo is looking light and simple for me.

Then For Is Working :

Then For Not Working :

Restful API delete and update both give me an error when try in postman :

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied.

I also add execption in config => filter.php

public $globals = [
            'before' => [
                //'honeypot'
                'csrf' => ['except' => [
                        'api/ApiManageMaintenance/delete'
                    ]
                ]           
            ],
    
        ];

I dont really understand the config filter.php but it seem this line of code will make the api delete working.

'csrf' => ['except' => [
                'api/ApiManageMaintenance/delete'
            ]
    ]       

Now my question are :

  1. Is there any specific setup or configuration I miss or I need to do for Restfu API to make API Restfull working ?

Any help from this community is very appreciate.


Solution

  • The Answer :

    Create File Filter in Folder Filters in Codeigniter 4

    Put this code :

    <?php
    
    namespace App\Filters;
    
    use CodeIgniter\HTTP\RequestInterface;
    use CodeIgniter\HTTP\ResponseInterface;
    use CodeIgniter\Filters\FilterInterface;
    use Codeigniter\API\ResponseTrait;
    use Config\Services;
    use Exception;
    
    
    class FilterBasicAuth implements FilterInterface
    {
    
        use ResponseTrait;
        public function before(RequestInterface $request, $arguments = null)
        {               
            
            header('Access-Control-Allow-Origin: *');
            header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
            
            $method = $_SERVER['REQUEST_METHOD'];
            if ($method == "OPTIONS") {
                die();
            }    
        }
    
        public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
        {
            // Do something here
        }
    }
    

    The main code is :

    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    
            $method = $_SERVER['REQUEST_METHOD'];
            if ($method == "OPTIONS") {
                die();
            }    
    

    Then in config Filters.php

    put and add aliases this code :

    public $aliases = [             
            'cors'     => \App\Filters\FilterBasicAuth::class,
        ];
    

    Note :

    I use filter name FilterBasicAuth. You can change to yours and make sure in the aliases change the name too.

    Thats All.