Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Authorisation in CakePHP 3

I have an intranet app running on IIS, using CakePHP 3. From IIS I am able to access the server var $_SERVER['AUTH_USER'] and I want to use this variable to authenticate users.

I have created a users table in my database with a username field that I want to match to AUTH_USER. I have created a custom Auth component like so:

namespace App\Auth;

use Cake\Auth\BaseAuthenticate;
use Cake\Network\Request;
use Cake\Network\Response;
use Cake\ORM\TableRegistry;

class AuthuserAuthenticate extends BaseAuthenticate
{
    public function authenticate(Request $request, Response $response) {
      $username = str_replace('DOMAIN\\', '', $_SERVER['AUTH_USER']);
      $users = TableRegistry::get('Users');
      $user = $users->find()->where(['username' => $username])->first();

      if ($user) {
        return $user;
      } else {
        $user = $this->Users->newEntity();
        $user->username = $username;
        if ($this->Users->save($user)) {
          return $user;
        } else {
          return false;
        }
      }
    }

And in the AppController initialize() I have tried to load Auth with the custom component.

$this->loadComponent('Auth', [
        'authenticate' => [
            'Basic' => [
                'fields' => ['username' => 'username'],
                'userModel' => 'Users'
            ],
        ],
        'loginAction' => [
            'controller' => 'Pages',
            'action' => 'display'
        ],
        'storage' => 'Memory',
        'unauthorizedRedirect' => false
    ]);
    $this->Auth->config('authenticate', 'Authuser');

At this point I just get redirected no matter what page I try to go on, I'm not really sure if it's failing to authenticate or something else is the problem.

I have tried adding this to AppController as a test:

public function isAuthorized($user)
  {
    return true;
  }

But I am unable to access any pages with this code in place. Can anyone let me know what I'm doing wrong?

Thanks,

Kez

like image 837
Kez Avatar asked Oct 29 '22 20:10

Kez


1 Answers

Your auth component is not implementing the authorize method.

public function authorize($user, Request $request) {
  // return true if authorized
  // return false if not authorized
}

Secondly, isAuthorized is called when using the ControllerAuthorize component. If you want to use controller authentication, you should use ControllerAuthorize insted.

$this->loadComponent('Auth', [
  'authenticate' => 'Controller'
]);

Also: You are configuring the BasicAuthenticate component, then immediately overwriting the config.

like image 103
jtrumbull Avatar answered Nov 15 '22 07:11

jtrumbull