CakePHP 2.1 - As a web application and REST servic

2019-04-02 14:00发布

问题:

I'm currently developing a CakePHP application which currently has form authentication. I would also like to open up this application for other applications to connect to via REST.

I know that CakePHP would be able to do this using the

Router::mapResources() 

and

Router::parseExtensions() 

However, I'm unsure how to get this working with say Basic or Digest HTTP authentication.

I've got the following in the AppController.php

public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form'
        ),
        'loginAction' => array(
            'admin' => false,
            'controller' => 'users',
            'action' => 'login'
        ),
        'loginRedirect' => array(
            'controller' => 'users',
            'action' => 'home'
        )
    )
);

If for the authenticate field, I had in 'Basic' for example - when logging into the web based version, I get an HTTP auth box and not the web based form.

What is the best way of doing this? The only way I can think of at the moment is to create a separate ApiController and manually do authentication?

Any advise would be awesome.

Update:

This is my revised code which is giving me the correct behavour - I'm pretty sure that there should be a better way to do this.

class AppController extends Controller {

    public $components = array(
        'Session',
        'RequestHandler',
        'Auth' => array(
            'loginAction' => array(
                'admin' => false,
                'controller' => 'users',
                'action' => 'login'
            ),
            'loginRedirect' => array(
                'controller' => 'users',
                'action' => 'home'
            )
        )
    );

    public $helpers = array('Html', 'Form', 'Session');

    public function beforeFilter() {
        $header = $_SERVER['HTTP_AUTHORIZATION'];
        if($header) {
            $this->Auth->authenticate = array('Basic');
        }
    }

}

回答1:

public function beforeFilter() {

    // Change the authentication if using REST
    if($this->params['ext'] == 'json') {
        $this->Auth->authenticate = array('Basic');
    }

}

This checks for a JSON extension, if the request contains it - then switch to Basic authentication.



回答2:

Check the Authentication chapter in the CakePHP book.

CakePHP supports Form, Basic, and Digest and you can create your own authentication objects and use them.

You can load multiple authentication objects and Cake will log the user in when the first of them returns true to the auth handler. You only have the Form auth object loaded, no idea why you get the http auth box. It is unlikely that Cake is the issue.