1. Go to this page and download the library: Download dakujem/auth-middleware 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/ */
$mwFactory = AuthWizard::factory(new Secret('a-secret-api-key-never-to-commit', 'HS256'), $app->getResponseFactory());
// Decode the token for all routes,
$app->add($mwFactory->decodeTokens());
// but only apply the assertion to selected ones.
$app->group('/foo', ...)->add($mwFactory->assertTokens());
AuthWizard::decodeTokens(__
// a combination of secret and the encryption algorithm used
new Secret('a-secret-api-key-never-to-commit', 'HS256'),
'token', // what attribute to put the decoded token to
'Authorization', // what header to look for the Bearer token in
'token', // what cookie to look for the raw token in
'token.error' // what attribute to write error messages to
);
AuthWizard::assertTokens(
$responseFactory, // PSR-17 Request factory
'token', // what attribute to look for the decoded token in
'token.error' // what attribute to look for error messages in
);
$inspector = function (object $token, callable $next, callable $withError): Response {
if ($token->sub === 42) { // Implement your inspection logic here.
return $next(); // Invoke the next middleware for valid tokens
} // or
return $withError('Bad token.'); // return an error response for invalid ones.
};
AuthWizard::inspectTokens(
$responseFactory, // PSR-17 Request factory
$inspector,
'token', // what attribute to look for the decoded token in
'token.error' // what attribute to look for error messages in
);
new TokenMiddleware(
// decode JWT tokens
new FirebaseJwtDecoder('a-secret-never-to-commit', ['HS256', 'HS512', 'HS384']),
[
// look for the tokens in the `Authorization` header
TokenManipulators::headerExtractor('Authorization'),
// look for the tokens in the `token` cookie
TokenManipulators::cookieExtractor('token'),
],
// target the `token` and `token.error` attributes for writing the decoded token or error message
TokenManipulators::attributeInjector('token', 'token.error')
);