Search code examples
cakephpoverridingbasic-authentication

CakePHP : override BasicAuthenticate.php


I'm trying to override lib/Cake/Controller/Component/Auth/BasicAuthenticate.php, because I need to change the unauthenticated() method.

So I copied and modified the file to app/Lib/Cake/Controller/Component/Auth/BasicAuthenticate.php (also tried without the 'Cake' folder), but the changes are not taken into account.

My edit works when modifying directly the core file but I'd rather not.

How should I do ? I'm using Cake 2.5


Solution

  • Check if you really need to override a core class

    To me this looks like you are on the wrong track, overriding the class shouldn't be neccesary unless for example you have no controler over where and how the basic authentication adapter is being used (for example in a plugin that doesn't offer configuration).

    If you'd really need to overwrite the class, then the path should be

    app/Lib/Controller/Component/Auth/BasicAuthenticate.php

    and it should work just fine (it does for me, using CakePHP 2.5.6).

    http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#overriding-classes-in-cakephp


    Use a custom authentication handler instead

    If you have control over the adapter configuration, the I'd suggest that you extend the BasicAuthenticate class instead, and only override the unauthenticate() method, and finally make the auth component use the custom adapter.

    Something like

    app/Controller/Component/Auth/CustomBasicAuthenticate.php

    App::uses('BasicAuthenticate', 'Controller/Component/Auth');
    
    class CustomBasicAuthenticate extends BasicAuthenticate {
        public function unauthenticated(CakeRequest $request, CakeResponse $response) {
            // do something special
        }
    }
    

    Controller

    public $components = array(
        'Auth' => array(
            'authenticate' => array(
                'CustomBasic'
            )
        )
    );
    

    See also the Creating Custom Authentication objects section in the Cookbook.