Laravel: Remove Request Throttling For Authenticated Users - laravel

I wish to disable request throttling for users that are authenticated through the API.
Kernel:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:240,1'
],
];
Throttle here will limit the requests to 240 per minute regardless of whether or not a user is authenticated.
How would it be possible to do this so it only throttles unauthenticated users?

For the latest version of Laravel 8.x. We can use RateLimiter with the following steps:
In your app/Providers/RouteServiceProvider.php find below configureRateLimiting:
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
// Add this for no limit throttle
RateLimiter::for('none', function (Request $request) {
return Limit::none();
});
}
In your app/web.php add 'throttle:none':
Route::group([
'middleware' => ['auth', 'throttle:none'],
], function ($router) {
Route::post('test', 'TestController#test');
});
This step is optional, If you are using other middleware you can group them up in your app/Http/Kernel.php:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'no_throttle' => [
'throttle:none',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Route::group([
'middleware' => ['auth', 'no_throttle'],
], function ($router) {
Route::post('test', 'TestController#test');
});

You could pack all auth routes to one group and set throttle to unlimited or in your controller class constructor you can disable ThrottleRequests middleware.
Please check this thread:
Disable rate limiter in Laravel?

Related

Laravel 5.8 null csrf_token() when used in api controller

I'm working on Laravel 5.8 and php 7.1.3. using csrf_token() return value in controller function but not return any value in controllers/api controller. how to used csrf_token in api controller function.
Api controller :- Http/Controllers/Api/TestConroller.php
class TestConroller extends Controller
{
public function __construct()
{
}
public function getToken(Request $request){
echo csrf_token();
}
}
Routes:- routes/api.php
Route::get('getToken', 'Api\TestConroller#getToken');
url:-
http://localhost/laravel/api/getToken
if csrf token() not work in api controller then how to used token for verification in api.
Csrf token only works in web.php not in api.php .Api's are stateless
if you check kernal.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\HandleInertiaRequests::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
web middleware uses session .So For testing purpose if you comment below middleware
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
then it will return null on web.php
if you want to use in api.php just add these 2 lines in kernel.php
\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
in
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
section

Auth::check() is always false in middleware in Laravel 5.7

I have used middlewares for many Laravel applications, but this is a stupid situation never happened to me before. The middleware always returns false for Auth::check()
This is routes of User module
<?php
Route::group(['middleware' => 'web', 'namespace' => 'Modules\User\Http\Controllers'], function () {
Route::get('/', 'UserController#index');
Route::get('login', 'LoginController#showLoginForm')->name('login');
Route::post('login', 'LoginController#login');
Route::post('logout', 'LoginController#logout')->name('logout');
});
Route::group(['middleware' => 'admin', 'prefix' => 'user', 'namespace' => 'Modules\User\Http\Controllers'], function () {
Route::get('register', 'RegisterController#showRegistrationForm')->name('register');
Route::post('register', 'RegisterController#register');
});
This is AdminMiddleware inside the User module
<?php
namespace Modules\User\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
$log = Auth::check();
dd($log);
return $next($request);
}
}
and this is kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \Modules\User\Http\Middleware\AdminMiddleware::class
];
But the result of dd($log) is always false. What is wrong here?!!!
You also need to add web middleware to User module routes group.
Because the session starts there.
Just saying, another solution is that you added it to the global middleware stack instead of the web middleware group! (Only add it to web, it can't be both)
please append your middleware address:
\Modules\User\Http\Middleware\AdminMiddleware::class
to
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Modules\User\Http\Middleware\AdminMiddleware::class //this is your middleware.
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
you can set your middleware's priority to be loaded after StartSession to be sure it will be loaded after the session starts.
in kernel.php
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Modules\User\Http\Middleware\AdminMiddleware::class
\App\Http\Middleware\Authenticate::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
\App\Http\Middleware\CheckProfileRequiredData::class, // putting CheckProfileRequiredData after Auth priority is required! to perform it's check after auth middleware
\App\Http\Middleware\CheckUserMustPayWithoutAnsweringDietRequiredQuestions::class,
];

Laravel session cookie not encrypted when using AJAX

I'm about to create a single-sign-on interface for my app. The other app sends an AJAX POST request and I authenticate the user and return a response. A session cookie is beeing set, but it is not encrypted.
The relevant Code
$user = User::where('email', $email)->first();
if ($user) {
Auth::login($user);
return response("OK", 200);
}
My 'api' part in Kernel.php
'api' => [
'throttle:60,1',
'bindings',
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\App\Http\Middleware\EncryptCookies::class,
],
My route (no additional Middleware)
Route::post(
'/auth-request', [
'uses' => 'UserController#post_authenticateRequest',
'as' => 'authrequest'
]);
The EncryptCookies class in Kernel.php doesn't seem to have any effect in the AJAX post request - but only for the session part. When I manually add a cookie like
response("OK", 200)->cookie("mysession", Session::getId(), 60);
it is encrypted!
When I completely remove EncryptCookies in Kernel.php for both "api" and "web" the created session from the AJAX request is loaded correctly - but without encryption anymore.
How do I get the AJAX session cookie beeing encrypted? Do I need any other Middleware?
Thanks for your help.
After reading the comment from lagbox, I've tried several places for the EncryptCookies::class definition in my "api" part. I need to place it not only before StartSession but as the first element. And now it works!
My complete $middlewareGroups part in Kernel.php now looks like this:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\App::class,
],
'api' => [
\App\Http\Middleware\EncryptCookies::class,
'throttle:60,1',
'bindings',
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
],
];
Hope this is helpfull.

Laravel 5.3 middleware execution order bug

I'm having a problem:
No matter what I do, the auth middleware is ALWAYS executed before other middlewares!
Here's what I tried:
Created a middleware named aa (so it comes before auth at least alphabetically).
I also put it before the auth one in Kernel.php
Then I created a nested route group:
Route::group(['prefix' => 'test', 'middleware' => 'aa'], function() {
Route::get('/', function() {
return 'test';
});
Route::group(['prefix' => 'test2', 'middleware' => 'auth:api'], function() {
Route::get('/', function() {
return 'test2';
});
});
});
If I go to /test/test2 the auth middleware gets executed before the aa one.
If I go to /test then I see the aa middleware is executed..
the middleware code is really easy:
public function handle($request, Closure $next)
{
dd('aa middleware!');
}
Here is Kernel.php as requested from #Rimon Khan
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'bindings',
],
];
protected $routeMiddleware = [
'aa' => \App\Http\Middleware\Aa::class,
'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
];
}
Edit: #prateekkathal you will never convert me to use spaces instead of tabs even if you force edit my post and change the indentation! lol
I got the answer. You should override the $middlewarePriority in your Kernel.php.
/**
* The priority-sorted list of middleware.
*
* Forces the listed middleware to always be in the given order.
*
* #var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];

\Auth::user() is null in 5.3.6?

This is about Laravel 5.3.6
I am able to login successfully and I can check Auth User after login. I can show the exact location where Auth::guard() has current user object. Below are the details.
Go to Login Controller
Go to AuthenticatesUsers Trait
Go to sendLoginResponse method. User reaches here successfully because user is authenticated successfully.
here I can check $this->guard()->user() has current user value. But when control reaches to Role controller....I tried to access it like this dd(Auth::guard()); and value was null. I also added reference below in Role Controller.
use Illuminate\Support\Facades\Auth;
Below is my route for Role Controller.
Route::group(['middleware' => ['auth']], function () {
Route::get('/Roles',
array (
'uses' => 'Website\Role\RoleController#index',
'as' => 'Roles'
)
);
});
Did you face this kind of issue in Laravel 5.3.6?
Output of \Auth::guard() is below.
SessionGuard {#162 ▼
#name: "web"
#lastAttempted: null
#viaRemember: false
#session: Store {#165 ▶}
#cookie: CookieJar {#167 ▶}
#request: Request {#40 ▶}
#events: Dispatcher {#5 ▶}
#loggedOut: false
#tokenRetrievalAttempted: false
#user: null
#provider: EloquentUserProvider {#158 ▶}
}
Kernel.php file was like below
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
I changed it to like below.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
protected $middlewareGroups = [
'web' => [
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];

Resources