How to implement API authentication in Phalcon?

Member

by gilbert , in category: PHP Frameworks , 2 years ago

How to implement API authentication in Phalcon?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , a year ago

@gilbert 

To implement API authentication in Phalcon, you can follow these steps:

  1. Create a middleware class that can authenticate the API requests.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use PhalconMvcMicro;
use PhalconMvcMicroMiddlewareInterface;

class AuthMiddleware implements MiddlewareInterface
{
    public function call(Micro $app)
    {
        $headers = $app->request->getHeaders();
    
        //check if the "Authorization" header exists
        if (!isset($headers['Authorization'])) {
            throw new Exception('Authorization header is missing', 401);
        }
    
        //parse the authorization token
        $authToken = trim(str_replace('Bearer', '', $headers['Authorization']));
    
        //verify the token against your authentication logic
        if (!verifyAuthToken($authToken)) {
            throw new Exception('Invalid authorization token', 401);
        }
    
        //pass the control to the next middleware
        $app->next();
    }
}


  1. Define your application routes and attach the AuthMiddleware to the routes that require authentication.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
$router = $di->get('router');
$router->add('/', [
    'controller' => 'Api',
    'action' => 'index'
]);
 
$app = new Micro();
 
//attach the AuthMiddleware to the "/data" route
$app->get('/data', function () use ($app) {
    return ['message' => 'You are authorized to access this route.'];
})->before(new AuthMiddleware());
 
//attach the AuthMiddleware to the "/secure-data" route
$app->get('/secure-data', function () use ($app) {
    return ['message' => 'This is a secure route that requires authentication.'];
})->before(new AuthMiddleware());
 
$app->handle();


  1. Finally, define the authentication logic in the verifyAuthToken function inside the AuthMiddleware class.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
private function verifyAuthToken($authToken)
{
    //validate the token against your API credentials
    $credentials = [
        'api_key' => 'YOUR_API_KEY',
        'api_secret' => 'YOUR_SECRET_KEY'
    ];
    
    //authenticate the token against the API credentials
    if ($authToken === base64_encode($credentials['api_key'] . ':' . $credentials['api_secret'])) {
        return true; //the token is valid
    }
    
    return false; //the token is invalid
}


That's it! You have implemented API authentication in Phalcon using a middleware class that verifies the "Authorization" header and checks it against your authentication logic.