【发布时间】:2021-07-01 23:22:09
【问题描述】:
我一直在 Laravel 中间件中使用一种方法来检查任何 URL 段中的字符串,如果它与“黑名单”字符串匹配,则阻止 IP。
一开始,我只有几个字符串要检查,但现在,列表越来越多,当我尝试优化它以使用 blacklist array 时,我最终在代码中一团糟,在我的想法。
我相信这是可以做到的,但无法找出优化此中间件的最佳方法。下面是一个中间件代码示例,其中包含我遇到问题的注释。
在handle($request, Closure $next) 方法中为所有列入黑名单的字符串调用$this->inUrl() 方法。
我尝试添加一个protected $blacklisted 数组,用于$this->inUrl(),但无法使其工作。
提前感谢您提出的任何建议,我们将不胜感激和欢迎。我还考虑在优化后将代码作为要点提供在 GitHub 上。
namespace App\Http\Middleware;
/**
* Class VerifyBlacklistedRequests
*
* @package App\Http\Middleware
*/
class VerifyBlacklistedRequests
{
/**
* The array of blacklisted request string segments
*
* @access protected
* @var array|string[]
*/
protected array $blacklisted = [
'.env', '.ftpconfig', '.vscode', ',git', '.git/HEAD'
// etc...
];
/**
* Handle an incoming request.
*
* @access public
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if($this->inUrl('.env')
|| $this->inUrl('.ftpconfig')
|| $this->inUrl('.vscode')
|| $this->inUrl('.git')
|| $this->inUrl('.git/HEAD')
// many more checks below the above ones
) {
// logic that blocks the IP goes here and working fine
}
return $next($request);
}
/**
* Check if the string is in any URL segment or at the one specified.
*
* @access protected
*
* @param string|mixed $value Segment value/content.
* @param integer $segment Segment position.
*
* @return bool
*/
protected function inUrl(string $value, $segment = -1)
{
if($segment !== -1 && request()->segment($segment) === $value) {
return true;
}
collect(request()->segments())->each(function ($segment) use ($value) {
if($segment === $value) {
return true;
}
});
return false;
}
}
【问题讨论】:
标签: laravel security optimization middleware blacklist