PHP code example of sinbadxiii / phalcon-auth-jwt

1. Go to this page and download the library: Download sinbadxiii/phalcon-auth-jwt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sinbadxiii / phalcon-auth-jwt example snippets


use Sinbadxiii\PhalconAuthJWT\Blacklist;
use Sinbadxiii\PhalconAuthJWT\Builder;
use Sinbadxiii\PhalconAuthJWT\Http\Parser\Chains\AuthHeaders;
use Sinbadxiii\PhalconAuthJWT\Http\Parser\Chains\InputSource;
use Sinbadxiii\PhalconAuthJWT\Http\Parser\Chains\QueryString;
use Sinbadxiii\PhalconAuthJWT\Http\Parser\Parser;
use Sinbadxiii\PhalconAuthJWT\JWT;
use Sinbadxiii\PhalconAuthJWT\Manager as JWTManager;


$di->setShared("jwt", function () {

    $configJwt = $this->getConfig()->path('jwt');

    $providerJwt = $configJwt->providers->jwt;

    $builder = new Builder();

    $builder->lockSubject($configJwt->lock_subject)
        ->setTTL($configJwt->ttl)
        ->setRequiredClaims($configJwt->builder, $manager, $parser);
});
 


namespace App\Models;

use Phalcon\Mvc\Model;
use Sinbadxiii\PhalconAuthJWT\JWTSubject;

class User extends Model implements JWTSubject
{

    //...
    
    public function getJWTIdentifier()
    {
        return $this->id;
    }

    public function getJWTCustomClaims()
    {
        return [
            "email" => $this->email,
            "username" => $this->username
        ];
    }
}

 


namespace App\Security\Access;

use Sinbadxiii\PhalconAuth\Access\AbstractAccess;

class Jwt extends AbstractAccess
{
    /**
     * @return bool
     */
    public function allowedIf(): bool
    {
        return $this->auth->parseToken()->check();
    }
}

$di->setShared("auth", function () {

    $security = $this->getSecurity();

    $adapter     = new \Sinbadxiii\PhalconAuth\Adapter\Model($security);
    $adapter->setModel(App\Models\User::class);

    $guard = new \Sinbadxiii\PhalconAuthJWT\Guard\JWTGuard(
        $adapter,
        $this->getJwt(),
        $this->getRequest(),
        $this->getEventsManager(),
    );

    $manager = new Manager();
    $manager->addGuard("jwt", $guard);
    $manager->setDefaultGuard($guard);

    $manager->setAccess(new \App\Security\Access\Jwt());
    $manager->except("/auth/login");

    return $manager;
});
 
    $application = new \Phalcon\Mvc\Micro($di);

    $eventsManager = new Manager();
   
    $application->post(
        "/auth/logout",
        function () {
            $this->auth->logout();

            return ['message' => 'Successfully logged out'];
        }
    );

    $application->post(
        "/auth/refresh",
        function () {
            $token = $this->auth->refresh();

            return $token->toResponse();
        }
    );

    $application->post(
        '/auth/login',
        function () {

            $credentials = [
                'email' => $this->request->getJsonRawBody()->email,
                'password' => $this->request->getJsonRawBody()->password
            ];

            $this->auth->claims(['aud' => [
                $this->request->getURI()
            ]]);

            if (! $token = $this->auth->attempt($credentials)) {
                return ['error' => 'Unauthorized'];
            }

            return $token->toResponse();
        }
    );

    $application->get(
        '/',
        function () {
            return [
                'message' => 'hello, my friend'
            ];
        }
    );
        
 


declare(strict_types=1);

namespace App\Controllers\Auth;

use Phalcon\Mvc\Controller;

class LoginController extends Controller
{
    public function loginAction()
    {
        $credentials = [
            'email' => $this->request->getJsonRawBody()->email,
            'password' => $this->request->getJsonRawBody()->password
        ];

        $this->auth->claims(['aud' => [
            $this->request->getURI()
        ]]);

        if (! $token = $this->auth->attempt($credentials)) {
            $this->response->setJsonContent(['error' => 'Unauthorized'])->send();
        }

        return $this->respondWithToken($token);
    }

    public function meAction()
    {
        $this->response->setJsonContent($this->auth->user())->send();
    }

    public function logoutAction()
    {
        $this->auth->logout();

        $this->response->setJsonContent(['message' => 'Successfully logged out'])->send();
    }

    public function refreshAction()
    {
         return $this->respondWithToken($this->auth->refresh());
    }

    protected function respondWithToken($token)
    {
        $this->response->setJsonContent($token->toResponse())->send();
    }
}

 


namespace App\Middlewares;

use Phalcon\Mvc\Micro\MiddlewareInterface;
use Phalcon\Mvc\Micro;

use function in_array;

class AuthMiddleware implements MiddlewareInterface
{
    public function call(Micro $application)
    {
        $authService = $application->getDI()->get("auth");

        if ($access = $authService->getAccess()) {
            $excepts = $access->getExceptActions();

            $uri = $application->getDI()->get("request")->getURI(true);

            if (!in_array($uri, $excepts)) {
                try {
                     $authService->parseToken()->checkOrFail();
                } catch (\Throwable $t) {
                    $responseService = $application->getDI()->get("response");
                    $responseService->setStatusCode(401, 'Unauthorized');
                    $responseService->setJsonContent(
                        [
                            "error" => "Unauthorized: " . $t->getMessage(),
                            "code" => 401
                        ]
                    );
                    if (!$responseService->isSent()) {
                        $responseService->send();
                    }
                }
            }
        }

        return true;
    }
}
 
$application = new \Phalcon\Mvc\Micro($di);

$eventsManager = new Manager();

$eventsManager->attach('micro', new AuthMiddleware());
$application->before(new AuthMiddleware());

$credentials = ['email' => '[email protected]', 'password' => '1234'];

$token = $this->auth->guard('api')->attempt($credentials);
 
// Generate a token for the user if the credentials are valid
$token = $this->auth->attempt($credentials);
 
// Get some user from somewhere
$user = User::findFirst(1);

// Get the token
$token = $this->auth->login($user);
 
// Get the currently authenticated user
$user =  $this->auth->user();
 
$this->auth->logout();
 
$newToken = $this->auth->refresh();
 
$this->auth->invalidate();
 
$token = $this->auth->tokenById(1);
 
$payload = $this->auth->payload();

// then you can access the claims directly e.g.
$payload->get('sub'); // = 1
$payload['jti']; // = 'sFF32fsDfs'
$payload('exp') // = 1665544846
$payload->toArray(); // = ['sub' => 1, 'exp' => 1665544846, 'jti' => 'sFF32fsDfs'] etc
 
if ($this->auth->validate($credentials)) {
    // credentials are valid
}
 
$token = $this->auth->claims(['username' => 'phalconist'])->attempt($credentials);
 
$user = $this->auth->setToken('eyJhb...')->user();
 
$this->auth->parseToken()->checkOrFail()