
In Slim4 Tutorial API middleware authentication , we will discuss how to check identity in JWT access token. This method is a process to prove user identity. It aims to provide access in order to give user authorized access. One of authentication method used is JWT access token from login API. Authentication does not require for public data. But for secure private data, authentication is necessary to prevent unauthorized persons from accessing the data.
Slim4 Middleware Authentication
Middleware of each framework has different flow and logic processes. In Slim4, the process is done by manipulating process between incoming requests and outgoing responses. In short, it can be used before or after calling the route. Based on the documentation, there are several ways to implement middleware is application, group, and route levels.
// Add Middleware On App
$app->add(new ExampleMiddleware());
// Add Middleware On Group
$app->group('/', function () { ... })->add(new ExampleMiddleware());
// Add Middleware On Route
$app->get('/', function () { ... })->add(new ExampleMiddleware());
JWT access token as authorization header
JWT access token that was generated by the API login will use for authentication media. It will be used at the authorization bearer token (authorization header) when sending a request. Furthermore, frontend or mobile apps use this method as an authentication process. Before the authentication process start, first add code on public/.htaccess to be able read the authorization header.
...
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Next in public/index.php file create function to implement the middleware:
...
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
...
$authMiddleware = function (Request $request, RequestHandler $handler) use ($settings) {
try {
$message = [];
if ($request->hasHeader('Authorization')) {
$header = $request->getHeader('Authorization');
if (!empty($header)) {
$bearer = trim($header[0]);
preg_match('/Bearer\s(\S+)/', $bearer, $matches);
$token = $matches[1];
$key = Key($settings['jwt']['key'], $settings['jwt']['alg']);
$data = JWT::decode($token, $key);
$dateTime = new DateTimeImmutable();
$now = $dateTime->getTimestamp();
if ($now > $data->nbf && $now < $data->exp) {
$request = $request->withAttribute('user_id', $data->user_id);
$request = $request->withAttribute('email', $data->email);
} else {
$message['message'] = 'Token expired';
}
}
} else {
$message['message'] = 'Unauthorized access';
$response = new \Slim\Psr7\Response();
$response->getBody()->write(json_encode($message));
return $response->withHeader('Content-Type', 'application-json')
->withStatus(401);
}
} catch (\Exception $e) {
$message['message'] = $e->getMessage();
$response = new \Slim\Psr7\Response();
$response->getBody()->write(json_encode($message));
return $response->withHeader('Content-Type', 'application-json')
->withStatus(401);
}
$response = $handler->handle($request);
return $response;
};
...
Middleware authentication on route
Middleware authentication in Slim4 can be implemented on route. Need to add ->add($authMiddleware) based on example given above. Create route with endpoint name is /identity. This route will show the logged user identity.
...
$app->get('/identity', function (Request $request, Response $response) {
$user = User::where('id', $request->getAttribute('user_id'))
->where('email', $request->getAttribute('user_email'))
->first();
$response->getBody()->write(json_encode($user));
return $response->withHeader('Content-Type', 'application/json')
->withStatus(200);
})->add($authMiddleware);
...
When accessing localhost/fashion-store-slim4/public/identity route without authorization bearer token, system will refuse and show message for Unauthorized access

Add access token that was generated by login API in authorization bearer token. Authorization bearer on Postman example:

Full code can be viewed at Github.
Pingback: Slim4 Fashion Store API: 5 Order API Menggunakan Database Transaction – PerangkatLunakKu
Pingback: Slim4 Tutorial API: 5 Database Transaction - PerangkatLunakKu
Pingback: Tutorial PHP Backend Slim4 - PerangkatLunakKu