2
votes

I have a REST API setup with CakePHP 1.3, which uses the Security component combined with the Auth component to facilitate HTTP Authentication for user login, like this:

UsersController:

function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('view', 'add');

    if ( $this->params['url']['ext'] == 'json' && !$this->Auth->user() ) {
        $this->Auth->allow('edit', 'add_friend');
        $this->Security->loginOptions = array(  
            'type'=>'basic',  
            'login'=>'authenticate',  
            'realm'=>'MyRealm'  
        );  
        $this->Security->loginUsers = array();  
        $this->Security->requireLogin('edit', 'add_friend');  
    }
}

AppController:

function authenticate($args) {  
    $data[ $this->Auth->fields['username'] ] = $args['username'];  
    $data[ $this->Auth->fields['password'] ] = $this->Auth->password($args['password']);  
    if ( $this->Auth->login($data) ) {
        return true;  
    } else {  
        $this->Security->blackHole($this, 'login');  
        return false;  
    }  
}

This is all working fine, my problem though is that I have a method which can optionally have authentication or not. It appears to me that the Security component in CakePHP has the requireLogin() method, which forces you to be authenticated.

I tried creating a new authenticate() method which always returned true:

function optionalAuthenticate($args) {  
    $data[ $this->Auth->fields['username'] ] = $args['username'];  
    $data[ $this->Auth->fields['password'] ] = $this->Auth->password($args['password']);  
    $this->Auth->login($data);
    return true;
}

But unfortunately that hasn't worked.

Does anyone know a way with the Security component that I can accomplish some kind of optional authorization?

1

1 Answers

0
votes

I ended up accomplishing this by not using the Security component at all, by declaring the optionalAuthenticate() method in the app_controller.php:

function optionalAuthenticate() { 
    if(empty($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_PW']))
        return false;
    $data[ $this->Auth->fields['username'] ] = $_SERVER['PHP_AUTH_USER'];  
    $data[ $this->Auth->fields['password'] ] = $this->Auth->password($_SERVER['PHP_AUTH_PW']);
    if($this->Auth->login($data))
        return true;
    else
        return false;
} 

And then just calling it from within whatever methods I want to attempt to authenticate (eg. in users_controller.php):

function view($id = null) {
    $this->optionalAuthenticate();
    $user = $this->Auth->user();
    if($user)
    ...