Reputation: 93
I started a project with slim3 framework. In my project I wrote a route group called admin
for administrators.
$app->group('/admin', function () use ($app) {
$app->add( new AdminMiddleWare() );
$app->get('/books/{id}', function ($request, $response, $args) {
...
});
});
any of administrators should send a GET token for validation . I want to create a middleware for checking admins tokens and if the token not set or is invalid display 403 error.
the Middleware class :
class AdminMiddleWare
{
/**
* Example middleware invokable class
*
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response
* @param callable $next Next middleware
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke($request, $response, $next)
{
???
}
}
can you help me?
Upvotes: 0
Views: 625
Reputation: 1342
First of all there's a small improvement that you can do to the way you're adding the middleware.
$app->group('/admin', function () use ($app) {
$app->get('/books/{id}', function ($request, $response, $args) {
...
});
})->add( new AdminMiddleWare() );
Attach the middleware to the group not to the entire app.
As for your question, you'll have the query params available in the request object.
i.e. for an URL like example.com/admin/books/12?token=sf342ad
you will have $params['token'] == 'sf342ad'
public function __invoke($request, $response, $next)
{
$params = $request->getQueryParams();
}
It might be easier to add the token as part of the route as you can generate the URL using reverse routing:
$app->group('/admin/{token}', function () use ($app) {
$app->get('/books/{id}', function ($request, $response, $args) {
...
})->setName('admin-book');
});
By doing it like this you'll have a token
key in the $args
array and it will match URLs like example.com/admin/sf342ad/books/1
And you can later build the route without hardcoding much:
$app->getContainer()->get('router')->pathFor('admin-book', ['token' =>'your token', 'id' => 'book id'])
Upvotes: 1