0

I don't want users to see the API data in the browser how do i stop them from accessing such a file

I have been researching but not sure if I am being clear in the search :)

<?php
  defined('BASEPATH') OR exit('No direct script access allowed');
  header('Access-Control-Allow-Origin: *');
class Api extends CI_Controller{
            public function __construct()
    {
        parent::__construct();

        $this->load->model('Api_model');
    }
   public function getFeed(){

     $result = $this->Api_model->getFeed();

     echo json_encode($result);
    }
}

1 Answers1

0

Before you move onto the concepts of API's you need to understand basic authentication.

Firstly in any user/role based application, your users will login and have their access restricted based on their role or authentication level. Creating an API doesn't change this fundamental issue. You may not necessarily enforce authentication on Public APIs not showing sensitive data. e.g(End point showing the latest Dollar to Pound Sterling conversion). Even with that request limitations are implemented based on a similar system.

Secondly I would not recommend creating your own API from scratch without having the in depth knowledge to cover security.

You can have a look at this library created specifically for CI: https://github.com/chriskacerguis/codeigniter-restserver

Although I would also recommend you look at framework agnostic Libraries that provide you with the same features and more.

A final option would be to provide the users with JWTokens as a means of authentication but like I said more knowledge on security would need to be understood in order to implement this safely and efficiently.

Good luck.

If you really wanted to maintain what you were doing you would do something like this:

<?php
  defined('BASEPATH') OR exit('No direct script access allowed');
  header('Access-Control-Allow-Origin: *');

  class Api extends CI_Controller{
            public function __construct()
    {
        parent::__construct();
        // ADDING AUTHENTICATION TO THE CONSTRUCTOR MEANS IT WILL RUN BEFORE ANY OTHER FUNCTION IS EXECUTED WITHIN THE CONTROLLER.
        userAuthenticate();     

        $this->load->model('Api_model');
    }

   public function getFeed(){
      $result = $this->Api_model->getFeed();
      echo json_encode($result);
    }
}
Enoch
  • 921
  • 6
  • 15