Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
\Security::check_token on REST api
  • Im developing REST api and would like to add token check function on each method: GET, POST, PUT, and DELETE.

    When a page is loaded, page will GET a set of data from the server for rendering.
    At that time, \Security::token_check() validates the token which is sent like
    http;//myproject.com?fuel_csrf_token=xxxxxxxxxxxxxxxxxxxxx.

    After fetching the data, when I try to update one of data records with PUT method, the app is failed because of \Security::check_token();

    I guess this is because all the time check_token() is fired, the token is changed to another.
    Is there any stylish way to handle this situation?

    Here is my trial solution.
    [base.php]
    >>
    <?php
    abstract class Controller_Base extends Controller_Rest {

        public $sent_token = '';
        public $cookie_token = '';
        public $msg = array( 'message' => 'Not authorised.' );

        public function before()
        {
            parent::before();

            $this->sent_token = \Input::param(\Config::get('security.csrf_token_key'));
            $this->cookie_token = \Input::cookie(\Config::get('security.csrf_token_key'));

            if (!Auth::check() || $this->sent_token !== $this->cookie_token)
            {
                $this->response($this->msg, 403);
                $this->response->send(true);
                exit();
            }
        }
    }
    << 

    [data.php]
    >>
    <?php
    class Controller_Data extends Controller_Base
    {
        public function before()
        {
            parent::before();
        }

        public function get_data()
        {
            // Do something
        }

        public function post_data()
        {
            // Do something
        }

        public function put_data()
        {
            // Do something
        }

        public function delete_data()
        {
            // Do something
        }
    }
    <<

    Thanks.
  • HarroHarro
    Accepted Answer
    Use Security::js_fetch_token() in your page.

    That will introduce the javascript function fuel_csrf_token(), which you can use to fetch the current valid token. Include that in your payload when the page submits the data.
  • That works! Thanks a million.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion