CakePHP form authentication for normal requests with basic authentication for JSON

心已入冬 提交于 2020-01-24 12:33:08

问题


I'm attempting to to build a web application that can be view by a user in a browser but also has an API for developers to interface with my application. My question is how do I change the authentication based on what type of request it is in CakePHP?

I would like my application to prompt users using the site with form authentication but when a request comes in with a '.json' to use basic authentication.

I've tried this in my AppController:

class AppController extends Controller {

public $components = array(
    'Session',
    'Auth' => array(
         'loginRedirect' => array(
             'controller' => 'journeys', 
             'action' => 'index'
             ),
        'logoutRedirect' => array(
            'controller' => 'pages', 
            'action' => 'display', 'home'
            )
    ),
    'RequestHandler'
);

public function beforeFilter() {
    if($this->params['ext'] == 'json') {
        $this->Auth->authenticate = array('Basic');
    } else {
        $this->Auth->authenticate = array('Form');
    }
    $this->Auth->allow('display'); 
}

}

I have checked that the clause in the beforeFilter if works and it does but I seem to get redirected to my form authentication no matter what URL I try and access in my application

The login function in my UsersController file looks like:

if ($this->Auth->login()) {
    return $this->redirect($this->Auth->redirect());
} else {
    $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}

I have read the docs on the CakePHP website but I can't seem to find an example that will help me. Any help would be appreciated.

EDITED FOR CORRECTION TO CODE AND MORE INFORMATION

I have carried on looking at this problem and Ive noticed that if I log the value of:

$this->Auth->authenticate

in the beforeFilter it says that it is basic but it's still sending me to the form log in.


回答1:


Excerp from the docs (see http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html):

Because basic and digest authentication don’t require an initial POST or a form so if using only basic / digest authenticators you don’t require a login action in your controller. Also you can set AuthComponent::$sessionKey to false to ensure AuthComponent doesn’t try to read user info from session.

So you do not require a login action. You could check for the authentication method in your users controller and skip the login action if the authentication method is "Basic".



来源:https://stackoverflow.com/questions/14587654/cakephp-form-authentication-for-normal-requests-with-basic-authentication-for-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!