php Laravel具有基本授权的用户的速率限制API

h5qlskok  于 2022-12-21  发布在  PHP
关注(0)|答案(2)|浏览(128)

我尝试在api.php中使用Basic Auth在API路由上设置用户速率限制,但似乎auth用户信息没有传递到RateLimiter,因为我收到错误消息“Attempt to read property id on null”。
RouteServiceProvider.php:

/**
 * Configure the rate limiters for the application.
 *
 * @return void
 */
protected function configureRateLimiting()
{

    RateLimiter::for('getRequest', function (Request $request) {
       
        return Limit::perMinute(2)->by($request->user()->id)->response(function(){
            
            return response()->json([
                'response' => 'failed',
                'message' => 'Too many request has been made',
            ],429);
        });
    });
}

api.php路径:

Route::middleware(['auth.basic.once'])->prefix('v1')->group(function() {
    Route::middleware(['throttle:getRequest'])->get('/animals/{id?}', [animalsApiController::class, 'show']);
});

我尝试使用Auth::user()-〉id,user()-〉id()和Auth::id()来代替$request-〉user()-〉id,但是同样的错误。有人能告诉我我是做错了什么还是遗漏了什么吗?
注:在控制器中检查$request-〉user()-〉id时,显示正常

vfwfrxfs

vfwfrxfs1#

RouteServiceProvider.php:

/**
 * Configure the rate limiters for the application.
 *
 * @return void
 */
protected function configureRateLimiting()
{
RateLimiter::for('getRequest', function (Request $request) {

dd(验证()-〉检查());

return Limit::perMinute(2)->by($request->user()->id)->response(function(){
        
        return response()->json([
            'response' => 'failed',
            'message' => 'Too many request has been made',
        ],429);
    });
});
}

首先检查登录用户

rqdpfwrv

rqdpfwrv2#

适用于使用Laravel 8或以上版本和密室生成代币的人。
下面的代码将有助于在您想要限制某些用户的地方实现速率限制。

protected function configureRateLimiting()
{
    RateLimiter::for('api', function (Request $request) {
        $rate_limit = 100;
        if(auth()->user()){
            $rate_limit = (isset(auth()->user()->rate_limit) ? auth()->user()->rate_limit : $rate_limit);
            return Limit::perMinute($rate_limit)->by(auth()->user()->id)->response(function(){
    
                return response()->json([
                    'response' => 'Failed',
                    'message' => 'Too many request has been made',
                ],429);
            });
        }else{
            return Limit::perMinute($rate_limit)->by($request->user()?->id ?: $request->ip())->response(function(){
                return response()->json([
                    'response' => 'Failed',
                    'message' => 'Too many request has been made',
                ],429);
            });
        }
    });
}

相关问题