Slim PHP: Only catch valid routes with middleware(超薄PHP:仅使用中间件捕获有效路由)
本文介绍了超薄PHP:仅使用中间件捕获有效路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用Slim编写一个REST API。我已经编写了一个小型中间件来保护资源,这样只有经过身份验证的用户才能访问它们:
<?php
class SecurityMiddleware extends SlimMiddleware
{
protected $resource;
public function __construct($resource)
{
$this->resource = $resource;
}
public function call()
{
//get a reference to application
$app = $this->app;
//skip routes that are exceptionally allowed without an access token:
$publicRoutes = ["/","/login","/about"];
if (in_array($app->request()->getPathInfo(),publicRoutes)){
$this->next->call(); //let go
} else {
//Validate:
if ($this->resource->isValid()){
$this->next->call(); //validation passed, let go
} else {
$app->response->setStatus('403'); //validation failed
$app->response->body(json_encode(array("Error"=>"Access token problem")));
return;
}
}
}
}
这是可行的,但不受欢迎的副作用是,中间件不区分现有的路由和不存在的路由。例如,如果用户尝试请求不存在的/dfghdfgh
这样的路由,他将得到一个403,表示没有访问令牌,而不是HTTP状态代码404。我想在中间件类上添加一个类似以下检查的实现:
if ($app->hasRoute($app->request->getPathInfo()){
$this->next->call(); //let go so user gets 404 from the app.
}
有什么想法可以实现这一点吗?
推荐答案
按照MamaWalter的建议,我使用hook来完成您想要做的事情,但是您希望使用slim.before.dispatch
而不是前面的钩子。如果您的用户尝试访问的路线不存在,则永远不会调用挂钩,并抛出404
。
我自己的Authorization Middleware就是这么做的。就像一种护身符。
这篇关于超薄PHP:仅使用中间件捕获有效路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:超薄PHP:仅使用中间件捕获有效路由


猜你喜欢
- PHP - if 语句中的倒序 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01