Laravel Kernel load dynamic middleware array - laravel

want edit my Kernel.php file and disabled some Middleware in on place in aplication (I want my header response was shortly, here is my stack subject)
I have some idea but i don't know what is the next step:
class Kernel extends HttpKernel
{
public function __construct(Application $app, Router $router)
{
$url = \Illuminate\Http\Request::capture()->url();
if($url == 'http://autoservie.test/save'){
//HERE i want set protected $middlewareGroup and remove session
middleware from 'web'
}else{
// HERE set another protected $middlewareGroup
}
parent::__construct($app, $router);
}
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:60,1',
'bindings',
],
];
The question is, how set dynamic protected $middlewareGroups array in constructor? Or is there any other solution ?

You can do something like
$index = array_search(\Illuminate\Session\Middleware\StartSession::class, $middlewareGroups['web']);
unset($middlewareGroups['web'][$index]);

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

Laravel: Remove Request Throttling For Authenticated Users

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?

Getting user id from Posts table

I have a route for destroying a Post, how can I make so that the one who can access the route is only the Post creator? For example, I have a Post with id number 3 and the user id is 5, so the only one who can delete number 3 is only user id 5. I've tried messing with middleware but not lucky enough to get it to work.
CekStatus.php (Middleware)
class CekStatus
{
public function handle($request, Closure $next)
{
$userId = $request->id;
$user = Post::where('id', $userId)->select('user_id')->pluck('user_id')->first();
if ($user === Auth::id()) {
return $next($request);
}
return redirect('/'); //redirect anyware.
}
}
Route
Route::get('/hapus/{id}','PostController#destroy')->middleware('cekstatus');
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,
'cekstatus' => \App\Http\Middleware\CekStatus::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
Output:
ERR_TOO_MANY_REDIRECTS
You should be using Policy here, the middleware is not used for authorization purposes. More on this in the docs here.
The docs use your example as well, instead of update you can create a delete function and then to use it in your controller you can add this:
if (auth()->user()->can('delete', $post)) {
// delete it code here.
}

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