$ php composer.phar require “cakephp/authorization:^2.0”
bootstrap() method in src/Application.php:
src/Application.php
$this->addPlugin('Authorization');
Enabling the Authorization Plugin
use Authorization\AuthorizationService; use Authorization\AuthorizationServiceInterface; use Authorization\AuthorizationServiceProviderInterface; use Authorization\Middleware\AuthorizationMiddleware; use Authorization\Policy\OrmResolver;
->add(new AuthorizationMiddleware($this));
public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface { $resolver = new OrmResolver(); return new AuthorizationService($resolver); }
lets add the AuthorizationComponent to AppController. In src/Controller/AppController.php add the following to the initialize() method.
public function initialize(): void { parent::initialize(); $this->loadComponent('Flash'); $this->loadComponent('Authentication.Authentication'); $this->loadComponent('Authorization.Autorization'); $this->loadComponent('RequestHandler'); $this->loadComponent('Flash'); }
Lastly we’ll mark the add, login, and logout actions as not requiring authorization by adding the following to src/Controller/UsersController.php
$this->Authorization->skipAuthorization();
Creating our First Policy
$ bin/cake bake policy –type entity Article
src/Policy/ArticlePolicy.php
namespace App\Policy; use App\Model\Entity\Article; use Authorization\IdentityInterface; class ArticlePolicy { public function canAdd(IdentityInterface $user, Article $article){ return true; } public function canEdit(IdentityInterface $user, Article $article){ return $this->isAuthor($user, $article); } public function canDelete(IdentityInterface $user, Article $article){ return $this->isAuthor($user, $article); } public function isAuthor(IdentityInterface $user, Article $article){ return $article->user_id === $user->getIdentifier(); } }
src/Controller/ArticlesController.php
public function add() { $article = $this->Articles->newEmptyEntity(); $this->Authorization->authorize($article); public function edit($slug) { $article = $this->Articles ->findBySlug($slug) ->contain('Tags') ->firstOrFail(); $this->authorization->authorize($article); public function delete($slug) { $this->request->allowMethod(['post', 'delete']); $article = $this->Articles->findBySlug($slug)->firstOrFail(); $this->Authorization->authorize($article);
add tag, view, index method
$this->Authorization->skipAuthorization();
なるほど、methodの中でAuthorizationを使うか使わないか記述するのね。