'CakePHP 3 basic authentication get authenticated user

get user

 public function beforeSave(Event $event) //for api
  {
    $hasher = new DefaultPasswordHasher();
            $entity->api_key_plain = 
             Security::hash(Security::randomBytes(32), 'sha256', false);
            $entity->api_key = $hasher->hash($entity->api_key_plain);
            return true;
}

 $this->loadComponent('Auth', [
            'authenticate' => [
                'Basic' => [
                    'fields' => ['username' => 'username', 'password' => 'api_key'],
                    //'finder'=>'apiauth',
                    'userModel'=>'Students',
                    
                ],
            ],
            'userModel'=>'Students',
            'storage' => 'Memory',
            'unauthorizedRedirect' => false,
        ]);






  public function getuser(){
       $user=$this->Auth->getUser(); // Auth getUser not found
        $header= $this->request->getHeader('Authorization'); 
       $usr =$this->Auth->user(); // Always return null
       return $this->jsonResponse($usr,200); 
    }

how to get authenticated user information form each request in CakePHP 3 AuthComponent

documentation : the getUser() method should return an array of user information on the success or false on failure.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source