How to create custom authorization in CakePHP?

by cortez.connelly , in category: PHP Frameworks , 2 years ago

How to create custom authorization in CakePHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 2 years ago

@cortez.connelly 

To create custom authorization in CakePHP, follow these steps:

  1. First, you need to create a custom authorization object by extending the BaseAuthorize class. You can do this by creating a new file in the src/Authorization folder of your CakePHP application.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace AppAuthorization;

use AuthorizationAuthorizationAuthorizationInterface;
use AuthorizationAuthorizationIdentityInterface;
use AuthorizationPolicyResultInterface;
use AuthorizationPolicyResult;

class CustomAuthorization implements AuthorizationInterface
{
    // Implement your custom authorization logic here
}


  1. Next, you need to configure your application to use your custom authorization object. You can do this in the config/bootstrap.php file by adding the following code:
1
2
3
4
5
6
use AuthorizationAuthorizationService;
use AppAuthorizationCustomAuthorization;

$authorization = new AuthorizationService();

$authorization->setAuthorizationChecker(new CustomAuthorization());


  1. Finally, you can use the AuthorizationService object in your controllers to check if a user is authorized to perform a certain action. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public function edit($id)
{
    $article = $this->Articles->get($id);

    if (!$this->Authorization->can($article, 'update')) {
        $this->Flash->error(__('You are not authorized to update this article.'));
        return $this->redirect(['action' => 'index']);
    }

    if ($this->request->is(['patch', 'post', 'put'])) {
        $article = $this->Articles->patchEntity($article, $this->request->getData());
        if ($this->Articles->save($article)) {
            $this->Flash->success(__('The article has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The article could not be saved. Please, try again.'));
    }
    $this->set(compact('article'));
}


In this example, the can() method of the AuthorizationService object is used to check if the user is authorized to update the specified article. If the user is not authorized, an error message is displayed and the user is redirected to the index page.