You can add a middleware that implements authorization before every request to your API: https://docs.phalcon.io/en/latest/reference/micro.html#middleware-events
It finally works. But because I search a lot after that, i add here more details
use Phalcon\Loader;
use Phalcon\Mvc\Micro;
use Phalcon\DI\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
use Phalcon\Http\Response;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Session\Adapter\Files as Session;
try{
// you need to start the session
// Start the session the first time when some component request the session service
$di->setShared('session', function () {
$session = new Session();
$session->start();
return $session;
});
And to make an authentication
// Create a events manager
$eventsManager = new EventsManager();
// Listen all the application events
$eventsManager->attach('micro', function ($event, $app) {
if ($event->getType() == 'beforeExecuteRoute') {
if ($app->session->get('auth') == false) {
try{
$connexion = $app->request->getJsonRawBody();
// Get the data from the user
$nomUsager = $connexion->nomUsager;
$motDePasse = $connexion->motDePasse;
// Find the user in the database - depends on your table
$utilisateur = membre::findFirst(
array(
"NomUsager = :nomUsager: AND MotDePasseMembre = :motDePasse:",
'bind' => array(
'nomUsager' => $nomUsager,
'motDePasse' => md5($motDePasse) //simplier
)
)
);
if ($utilisateur != false) {
$app->session->set(
'auth',
array(
'id' => $utilisateur->id,
'NomMembre' => $utilisateur->NomMembre,
'PrenomMembre' => $utilisateur->PrenomMembre
)
);
$app->flash->success('Bienvenue ' . $utilisateur->PrenomMembre);
return true;
}else{
$app->flash->error('Mauvais usager/mot de passe');
return false;
}
}
catch (Exception $e) {
//Create a response