Laravel速率限制返回JSON有效负载


Laravel rate limit to return a JSON payload

我正在Laravel之上构建一个API。我想通过使用Throttle中间件来使用内置的速率限制功能。

问题是,当节流中间件触发响应时:

// Response headers
Too Many Attempts.

我的API在JSON中使用了一个错误负载,如下所示:

// Response headers
{
  "status": "error",
  "error": {
    "code": 404,
    "message": "Resource not found."
  }
}

Throttle中间件以我需要的方式返回输出的最佳方法是什么?

创建您自己的闪亮中间件,通过原始扩展它,并覆盖您喜欢被覆盖的方法。

$ php artisan make:middleware ThrottleRequests

打开kernel.php并删除(注释掉)原始中间件并添加您的。

ThrottleRequests.php

<?php
namespace App'Http'Middleware;
use Closure;
class ThrottleRequests extends 'Illuminate'Routing'Middleware'ThrottleRequests
{
    protected function buildResponse($key, $maxAttempts)
    {
        return parent::buildResponse($key, $maxAttempts); // TODO: Change the autogenerated stub
    }
}

kernel.php

.
.
.
protected $routeMiddleware = [
    'auth' => 'Illuminate'Auth'Middleware'Authenticate::class,
    //'auth.basic' => 'Illuminate'Auth'Middleware'AuthenticateWithBasicAuth::class,
    'bindings' => 'Illuminate'Routing'Middleware'SubstituteBindings::class,
    'can' => 'Illuminate'Auth'Middleware'Authorize::class,
    'guest' => 'App'Http'Middleware'RedirectIfAuthenticated::class,
    //'throttle' => 'Illuminate'Routing'Middleware'ThrottleRequests::class,
    'throttle' => 'App'Http'Middleware'ThrottleRequests::class
];

我知道这是一个非常古老的问题,但是我有一个非常简短的解决方案。

我们可以在Handler.php中捕获并处理ThrottleRequestsException,而不是创建新的中间件,并相应地返回JSON响应。

应用程序异常' ' Hanlder.php

<?php
namespace App'Exceptions;
use Illuminate'Foundation'Exceptions'Handler as ExceptionHandler;
use Throwable;
use Request;
use Illuminate'Database'Eloquent'ModelNotFoundException;
use Illuminate'Http'Exceptions'ThrottleRequestsException;
class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];
    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];
    /**
     * Report or log an exception.
     *
     * @param  'Throwable  $exception
     * @return void
     *
     * @throws 'Throwable
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }
    /**
     * Render an exception into an HTTP response.
     *
     * @param  'Illuminate'Http'Request  $request
     * @param  'Throwable  $exception
     * @return 'Symfony'Component'HttpFoundation'Response
     *
     * @throws 'Throwable
     */
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof ThrottleRequestsException && $request->wantsJson()) {
            return json_encode([
                'message' => 'Too many attempts, please slow down the request.',
                'status' => false
            ]);
        }
        return parent::render($request, $exception);
    }
}

app/Http/Middleware/中创建一个新文件ApiThrottleRequests.php并粘贴下面的代码:

<?php
namespace App'Http'Middleware;
use Closure;
use Illuminate'Cache'RateLimiter;
use Symfony'Component'HttpFoundation'Response;
class ApiThrottleRequests
{
/**
 * The rate limiter instance.
 *
 * @var 'Illuminate'Cache'RateLimiter
 */
protected $limiter;
/**
 * Create a new request throttler.
 *
 * @param  'Illuminate'Cache'RateLimiter $limiter
 */
public function __construct(RateLimiter $limiter)
{
    $this->limiter = $limiter;
}
/**
 * Handle an incoming request.
 *
 * @param  'Illuminate'Http'Request $request
 * @param  'Closure $next
 * @param  int $maxAttempts
 * @param  int $decayMinutes
 * @return mixed
 */
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
{
    $key = $this->resolveRequestSignature($request);
    if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
        return $this->buildResponse($key, $maxAttempts);
    }
    $this->limiter->hit($key, $decayMinutes);
    $response = $next($request);
    return $this->addHeaders(
        $response, $maxAttempts,
        $this->calculateRemainingAttempts($key, $maxAttempts)
    );
}
/**
 * Resolve request signature.
 *
 * @param  'Illuminate'Http'Request $request
 * @return string
 */
protected function resolveRequestSignature($request)
{
    return $request->fingerprint();
}
/**
 * Create a 'too many attempts' response.
 *
 * @param  string $key
 * @param  int $maxAttempts
 * @return 'Illuminate'Http'Response
 */
protected function buildResponse($key, $maxAttempts)
{
    $message = json_encode([
        'error' => [
            'message' => 'Too many attempts, please slow down the request.' //may comes from lang file
        ],
        'status' => 4029 //your custom code
    ]);
    $response = new Response($message, 429);
    $retryAfter = $this->limiter->availableIn($key);
    return $this->addHeaders(
        $response, $maxAttempts,
        $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
        $retryAfter
    );
}
/**
 * Add the limit header information to the given response.
 *
 * @param  'Symfony'Component'HttpFoundation'Response $response
 * @param  int $maxAttempts
 * @param  int $remainingAttempts
 * @param  int|null $retryAfter
 * @return 'Illuminate'Http'Response
 */
protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null)
{
    $headers = [
        'X-RateLimit-Limit' => $maxAttempts,
        'X-RateLimit-Remaining' => $remainingAttempts,
    ];
    if (!is_null($retryAfter)) {
        $headers['Retry-After'] = $retryAfter;
        $headers['Content-Type'] = 'application/json';
    }
    $response->headers->add($headers);
    return $response;
}
/**
 * Calculate the number of remaining attempts.
 *
 * @param  string $key
 * @param  int $maxAttempts
 * @param  int|null $retryAfter
 * @return int
 */
protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter = null)
{
    if (!is_null($retryAfter)) {
        return 0;
    }
    return $this->limiter->retriesLeft($key, $maxAttempts);
}

}

然后转到app/Http/目录下的kernel.php文件,替换
'throttle' => 'Illuminate'Routing'Middleware'ThrottleRequests::class,

'throttle' => 'App'Middleware'ApiThrottleRequests::class,

并使用

middleware('throttle:60,1')

或添加

'apiThrottle' => 'App'Http'Middleware'ApiThrottleRequests::class,

你可以这样用

middleware('apiThrottle:60,1')

和帮助链接

https://thedevsaddam.gitbooks.io/off-time-story/how_to_customize_laravel_throttle_message_response.html

所以我所做的是创建一个扩展ThrottleRequest中间件的自定义中间件。您可以覆盖handle函数来检查请求,看看它是否期望JSON作为响应。如果是,调用buildJsonResponse函数,它将格式化JSON 429响应。你可以在buildJsonResponse中定制JsonResponse来满足你的API需求。

这允许您的节流中间件处理JSON和其他响应。如果请求期望JSON,它将返回JSON响应,否则,它将返回标准的"尝试次数过多"。明文反应。

请注意这来自Laravel 5.6。x ThrottleRequests中间件,并且基类可能已经更改。

编辑:

修复了在请求不期望JSON响应但请求被限制的情况下调用错误方法的问题。应该是$this->buildException($key, $maxAttempts);而不是$this->buildResponse($key, $maxAttempts);

<?php

namespace App'Http'Middleware;
use Closure;
use Illuminate'Http'JsonResponse;
use Illuminate'Routing'Middleware'ThrottleRequests;
class ThrottlesRequest extends ThrottleRequests
{
    /**
     * Handle an incoming request.
     *
     * @param  'Illuminate'Http'Request  $request
     * @param  'Closure  $next
     * @param  int  $maxAttempts
     * @param  float|int  $decayMinutes
     * @return mixed
     */
    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
    {
        $key = $this->resolveRequestSignature($request);
        if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
            // If the request expects JSON, build a JSON response, otherwise build standard response
            if ($request->expectsJson()) {
                return $this->buildJsonResponse($key, $maxAttempts);
            } else {
                return $this->buildException($key, $maxAttempts);
            }
        }
        $this->limiter->hit($key, $decayMinutes);
        $response = $next($request);
        return $this->addHeaders(
            $response, $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts)
        );
    }
    /**
     * Create a 'too many attempts' JSON response.
     *
     * @param  string  $key
     * @param  int  $maxAttempts
     * @return 'Symfony'Component'HttpFoundation'Response
     */
    protected function buildJsonResponse($key, $maxAttempts)
    {
        $response = new JsonResponse([
            'error' => [
                'code' => 429,
                'message' => 'Too Many Attempts.',
            ],
        ], 429);
        $retryAfter = $this->limiter->availableIn($key);
        return $this->addHeaders(
            $response, $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
            $retryAfter
        );
    }
}

对于在laravel 8上的任何人:

 RateLimiter::for("verify",function(Request $request){
        return Limit::perMinute(2)->by($request->ip())->response(function(){
            return response()->json(["state"=>false,"error"=>"Youve tried too many times"],200);
        });
    });

然后将油门中间件添加到你的路由