Created
March 31, 2025 13:55
-
-
Save ghostwriter/7b70387b325f85d8129838f48dd3e49d to your computer and use it in GitHub Desktop.
A custom middleware that delegates authentication to a specific adapter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
}, | |
], | |
], | |
]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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