Christopher Francisco
Christopher Francisco

Reputation: 16268

CakePHP basic auth on API (json) request

I want to make a request to resource/index.json, but since I index is not allowed without authentication it redirects me to login page. That's the behavior I want when no username:password has been sent

The thing is how do I set AuthComponent to work with both Form and Basic and only check for basic when the request goes through api prefix.

Also, does it automatically authenticate when found username and password in the header or do I have to do it manually?

Upvotes: 1

Views: 796

Answers (2)

Christopher Francisco
Christopher Francisco

Reputation: 16268

I decided to use Friend's of Cake TokenAuthenticate, and yes, it works along with FormAuthenticate so I am able to use both.

As a matter of fact, it automatically chooses the component it's going to use based on if there is an existing _token param or a X-MyApiTokenHeader header.

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form',
            'Authenticate.Token' => array(
                'parameter' => '_token',
                'header' => 'X-MyApiTokenHeader',
                'userModel' => 'User',
                'scope' => array('User.active' => 1),
                'fields' => array(
                    'username' => 'username',
                    'password' => 'password',
                    'token' => 'public_key',
                ),
                'continue' => true
            )
        )
    )
);

Upvotes: 0

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4142

in respective controller add few lines

class NameController extends AppController {
    public function beforeFilter() {
            parent::beforeFilter();
            $this->Auth->allow("index");
        }
}

This will allow index without authentication.

Upvotes: 2

Related Questions