dev-master
9999999-devTokenAuth plugin for CakePHP
MIT
The Requires
- php >=5.5.9
- cakephp/cakephp >=3.3.2 <4.0.0
The Development Requires
TokenAuth plugin for CakePHP
This is the plugin for make an authentication done with Tokens., (*1)
You can install the plugin by manually download, or by composer, (*2)
composer require falco442/cakephp-3-token-auth
Put into the table you use for authentication model ('users') the fields 'token' (varchar(255)) and 'token_created' (datetime)., (*3)
Load the plugin by calling, (*4)
Plugin::loadAll();
or, (*5)
Plugin::load('TokenAuth');
and put the Authentication object in your AppController.php
:, (*6)
public function initialize(){ parent::initialize(); // ... $this->loadComponent('Auth',[ 'authenticate'=>[ 'TokenAuth.Token' ], 'unauthorizedRedirect'=>false, 'storage'=>'Memory' ]); // ... }
Keep in mind that you can customize the Authentication object with the same parameters you would have used with FormAuthenticate, like userModel
and fields
, (*7)
You can set up the login action for your controller; for example, the action login()
in UsersController.php
:, (*8)
public function login(){ $user = $this->Auth->identify($this->request,$this->response); $this->set(compact('user')); $this->set('_serialize',['user']); }
Since the token authentication is done mainly for API applications, all you need is to retrieve the $user
object that contains the new token that TokenAuth automatically generates. This token will be used to do all the calls to the actions that you don't want to be publicly accessible., (*9)
If you want an action to be public, simply use, (*10)
$this->Auth->allow(['action-name']);
in the initialize()
method in respective controller., (*11)
The non-public routes that a client will call shall be of the form, (*12)
GET /uri.json?token=token-received
You can reset token by calling the shell, (*13)
cd cake-root ./bin/cake TokenAuth.token refresh
Note:
* the reset token task will take '-15 days' as base token life, but you can customize the shell
* the shell take the model User
as base, but you can set any model you like, (*14)
Type in console, (*15)
cd cake-root ./bin/cake TokenAuth.token refresh --help
to get some help, (*16)
Since we use (mainly) token authentication for api web applications, it is useful to set REST in CakePHP (see this page)., (*17)
This is done with simple steps:, (*18)
cake-root/app/Config/routes.php
by adding Router::parseExtensions('json','xml');
(or with the extensions you desires)cake-root/app/Controller/AppController.php
add the RequestHandler
component; it will parse the extension of the format (json, xml, ...)Router::mapResources()
, to be put in cake-root/app/Config/routes.php
TokenAuth plugin for CakePHP
MIT