我使用laravel 5.4,我想限制下面的路线请求
Route::group(['middleware' => ['throttle:2']], function () {
Route::post('/xxx', 'TestController@getTest');
});
效果很好,但收到的时间太多,尝试次数过多。"它显示在一个空白页面上。有没有办法在刀片视图中显示会话闪存消息?
答案 0 :(得分:1)
因此,一个简单的方法是更改您的油门中间件。
首先,创建一个新的中间件,扩展基本的节流中间件,如下所示:
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ThrottleRequests as
BaseThrottleRequests;
class ThrottleRequests extends BaseThrottleRequests
{
}
然后在app / Http / Kernel.php中更改你的油门中间件:
'throttle' => \App\Http\Middleware\ThrottleRequests::class
它现在将使用您自己的油门中间件,当它从laravel中延伸时,它具有其功能并且像以前一样工作。
然后,查看基类,你会发现buildResponse
在出现太多Attemps的情况下构建响应。因此,您只需要在中间件中覆盖它:
protected function buildResponse($key, $maxAttempts)
{
$retryAfter = $this->limiter->availableIn($key); // This gives you the number of seconds before the next time it is available
return redirect('test')->with('error', '...'); // You can use redirect() and all those stuffs as you would normally do to redirect the user and set a session message
}
答案 1 :(得分:0)
创建一个中间件,例如CustomThrottleRequests 在其中扩展ThrottleRequests中间件
覆盖句柄方法
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1, $prefix = '')
{
$key = $prefix.$this->resolveRequestSignature($request);
$maxAttempts = $this->resolveMaxAttempts($request, $maxAttempts);
if ($this->limiter->tooManyAttempts($key, $maxAttempts)) {
$retryAfter = $this->getTimeUntilNextRetry($key);
$retryAfter is in seconds
//here you can change response according to requirements
return redirect()->back()->withInput()->with('error','Too Many Attempts. Please try after '.$retryAfter .' seconds');
}
$this->limiter->hit($key, $decayMinutes * 60);
$response = $next($request);
return $this->addHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
}
现在在app / Http / Kernel.php中
change from
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
to
'throttle' => CustomThrottleRequests::class,