Authentication

Configure AuthManager

<?php

use PhalconRest\Constants\Services;
use PhalconRest\Auth\Manager as AuthManager;
use App\Auth\UsernameAccountType;

$di->setShared(Services::AUTH_MANAGER, function () use ($config) {

    $authManager = new AuthManager($config->authentication->expirationTime);

    $authManager->registerAccountType(UsernameAccountType::NAME, new UsernameAccountType());

    return $authManager;

});

Add account types

Different account types may be added by creating a class that implements PhalconRest\Auth\AccountType. This interface requires you to provide a login and an authenticate method.

For example App\Auth\UsernameAccountType class, which can be found in the phalcon-rest-boilerplate.

<?php

namespace App\Auth;

use App\Constants\Services;
use Phalcon\Di;
use PhalconRest\Auth\Manager;

class UsernameAccountType implements \PhalconRest\Auth\AccountType
{
    const NAME = "username";

    public function login($data)
    {
        /** @var \Phalcon\Security $security */
        $security = Di::getDefault()->get(Services::SECURITY);

        $username = $data[Manager::LOGIN_DATA_USERNAME];
        $password = $data[Manager::LOGIN_DATA_PASSWORD];

        /** @var \User $user */
        $user = \User::findFirst([
            'conditions' => 'username = :username:',
            'bind' => ['username' => $username]
        ]);

        if(!$user){
            return null;
        }

        if(!$security->checkHash($password, $user->password)){
            return null;
        }

        return (string)$user->id;
    }

    public function authenticate($identity)
    {
        return \User::existsById((int)$identity);
    }
}

Middleware

The middleware can be instantiated as follows:

<?php

use PhalconRest\Middleware\AuthenticationMiddleware;

$eventsManager->attach('micro', new AuthenticationMiddleware);

Authentication Flow

Step 1 - Authenticate using a account type

For this purpose we’ve created the PhalconRest/Auth/Manager which will store the session information for the duration of the request.

<?php

use App\Auth\UsernameAccountType;

/**
 * Authenticate user using username and password (Username Account)
 */

/** @var \PhalconRest\Auth\Manager $authManager */
$session = $authManager->loginWithUsernamePassword(UsernameAccountType::NAME, $username, $password);
On failure it will throw an exception (ErrorCodes::AUTH_BADLOGIN)

Step 2 - Receive session

After we’ve successfully authenticated we retrieve the PhalconRest/Auth/Session which we then use to create a response.

<?php

/** @var \PhalconRest\Auth\Session $session */

$session = $this->authManager->getSession();

$response = [
    'token' => $session->getToken(),
    'expires' => $session->getExpirationTime()
];

Step 3 - Store session

Because REST applications are supposed to be stateless, the session needs to be stored on the client.

Step 4 - Make subsequent request using the stored session

We can now authenticate any further requests using the received token from the initial authentication. authenticateToken() will throw a new new Exception(ErrorCodes::AUTH_BADTOKEN) when an invalid token has been given or a new Exception(ErrorCodes::AUTH_EXPIRED) when the session token has been expired.

<?php

/** @var \PhalconRest\Http\Request $request */
$token = $this->request->getToken();

if ($token) {
    $this->authManager->authenticateToken($token);
}

We’ve already incorporated the logic above in it’s own piece of middleware. Read more on our middleware.

AuthManager

loggedIn()

The loggedIn methods checks if there has been any session set.

<?php

if ($this->authManager->loggedIn()) {

    // Do something

}

getSession()

The getSession() method returns the current session.

<?php

if ($this->authManager->loggedIn()) {

    $session = $this->authManager->getSession();

}

Session

getIdentity()

<?php

if ($this->authManager->loggedIn()) {

    $session = $this->authManager->getSession();

    $userId = $session->getIdentity(); // For example; 1

    $user = \Users::findFirstById($userId);

}

The identity has been set after successful authentication by the given account type. In this case it’s the user’s id.