Skip to content

Instantly share code, notes, and snippets.

@ghostwriter
Created March 31, 2025 13:55
Show Gist options
  • Save ghostwriter/7b70387b325f85d8129838f48dd3e49d to your computer and use it in GitHub Desktop.
Save ghostwriter/7b70387b325f85d8129838f48dd3e49d to your computer and use it in GitHub Desktop.
A custom middleware that delegates authentication to a specific adapter.
<?php
return [
'dependencies' => [
'factories' => [
'BasicAuthMiddleware' => function (ContainerInterface $container): CustomAuthenticationMiddleware {
$adapter = $container->get(BasicAuthAdapter::class);
return new CustomAuthenticationMiddleware($adapter);
},
'OAuth2Middleware' => function (ContainerInterface $container): CustomAuthenticationMiddleware {
$adapter = $container->get(OAuth2Adapter::class);
return new CustomAuthenticationMiddleware($adapter);
},
],
],
];
<?php
final readonly class CustomAuthenticationMiddleware implements MiddlewareInterface
{
public function __construct(
private AuthenticationInterface $adapter
) {}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$user = $this->adapter->authenticate($request);
if (! $user instanceof UserInterface) {
return $this->adapter->unauthorizedResponse($request);
}
return $handler->handle($request->withAttribute(UserInterface::class, $user));
}
}
<?php
$app->get('/api/resource', ['BasicAuthMiddleware'], 'api.resource');
$app->get('/oauth2/resource', ['OAuth2Middleware'], 'oauth2.resource');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment