CakePHP 3 User Authorization

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

I created a user table in my database with the username field that I want to map to AUTH_USER. I created my own Auth component, for example:

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 AppController, initialize()I tried to load Auth using a 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'm just being redirected no matter what page I'm trying to continue on, I'm not sure if it is not authenticated or something else is not a problem.

I tried adding this to the AppController as a test:

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

- . - , ?

,

+4
1

auth authorize.

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

-, isAuthorized ControllerAuthorize. , ControllerAuthorize insted.

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

: BasicAuthenticate, .

+2

Source: https://habr.com/ru/post/1653667/


All Articles