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

时间:2016-10-25 18:05:30

标签: php laravel laravel-5 laravel-5.3

我在Laravel之上构建API。我希望使用Throttle中间件来使用内置的速率限制功能。

问题是,当油门中间件触发响应时:

// Response headers
Too Many Attempts.

我的API使用JSON中的错误有效内容,如下所示:

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

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

3 个答案:

答案 0 :(得分:8)

制作自己的闪亮中间件,按原件扩展,并覆盖您想要覆盖的方法。

$ 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
];

答案 1 :(得分:1)

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

这允许您的限制中间件处理JSON和其他响应。如果请求期望JSON,它将返回json响应,否则它将返回标准的“Too Many Attempts”明文响应。     

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->buildResponse($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
        );
    }
}

答案 2 :(得分:0)

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