Laravel Middleware changing header before passing to controller - laravel

I'm trying to change the header of my request before passing it to the controller using a middleware but it seems $next($request) executes the code in my controller. Is there a way to change the header then send the updated request to my controller?
My middleware:
class JWTAuthenticator
{
public function handle($request, Closure $next)
{
$token =JWTAuth::getToken();
$my_new_token = JWTAuth::refresh($token);
//it runs here
$response = $next($request);
//it runs this part after executing the controller
$response->header('Authorization','Bearer '.$my_new_token);
return $response;
}
This is how the middleware is assigned to my route:
Route::get('/{user}', 'v1\UserController#find')->middleware('jwt_auth');

That way you are excecuting the $response->header('Authorization','Bearer '.$my_new_token); sentence after the request was attended.
Change your code as follows:
class JWTAuthenticator
{
public function handle($request, Closure $next)
{
$token =JWTAuth::getToken();
$my_new_token = JWTAuth::refresh($token);
$request->headers->set('Authorization','Bearer '.$my_new_token);
return $next($request);
}

Related

debug adding header in middleware laravel

i added header in middleware and i want to check in my controller that header that i set exists or not . the problem i cant watch headers in controller debugging? how can i do that? anyway use case for this is cors problem
this is my middleware:
public function handle(Request $request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*');
}
and this is my controller:
public function action()
{
dd(request()->headers->get("Access-Control-Allow-Origin")); //always null
}
You need to call the set method:
public function handle(Request $request, Closure $next)
{
$request->headers->set('Access-Control-Allow-Origin', '*');
return $next($request);
}
Then you can retrieve the header:
public function action()
{
dd(request()->headers->get("Access-Control-Allow-Origin")); // *
}

Laravel - Delete Cookie in Middleware

I have a middleware in my project that call in every request. It will check if Request has a specific cookie, then delete another cookie. But it seems Cookies are not forgotten or set in Laravel until return in the response. something like
return response('view')->withCookie($cookie); that is not possible in middlewares.
Also I tried Cookie::queue(Cookie::forget('myCookie')); nothing happened and cookie is shown in my browser.
This is my middleware handle method:
public function handle(Request $request, Closure $next)
{
if (! $request->cookie('clear_token')) {
cookie()->forget('access_token'); # not worked
Cookie::queue(Cookie::forget('access_token')); # not worked
}
return $next($request);
}
You can change the response in middleware too:
https://laravel.com/docs/5.0/middleware
<?php namespace App\Http\Middleware;
class AfterMiddleware implements Middleware {
public function handle(\Illuminate\Http\Request $request, \Closure $next)
{
$response = $next($request);
// Forget cookie
return $response;
}
}

laravel terminable middleware, pass parameters from controller

I want to use a terminable middleware for request logging:
<?php
namespace Illuminate\Session\Middleware;
use Closure;
use App\Helpers\Logger;
class LogRequest
{
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
Logger::log($request, $response, $additionalInfo)
}
}
How can I pass the $additionalInfo from the controller to the middleware?
EDIT:
Unfortunately the additional info is generated in the controller. I therefore cannot hard code it in the route middleware function
Have you try to add to kernel.php:
protected $routeMiddleware = [
......
'LogRequest'=> \App\Http\Middleware\LogRequest::class
];
in the LogRequestMiddleware:
public function handle($request, Closure $next, $additionalInfo)
{
//here you have $additionalInfo
$request->attributes->add(["info" => $additionalInfo]);
return $next($request);
}
public function terminate($request, $response)
{
dd( $request->attributes);
}
And in controller:
public function __construct()
{
$additionalInfo = "test"
$this->middleware("LogRequest:$additionalInfo");
}
I think you can set some attribute to the request object in your controller while handling it, and the request object itself will be passed to terminate($request, $response) as the first parameter. Then you can extract whatever you set in your controller and use it.
Edited: You might be able to do this
Controller
$request->attributes->add(['additionalInfo' => 'additionalInfoValue']);
Middleware
public function terminate($request, $response)
{
$additionalInfo = $request->attributes('additionalInfo' => $additionalInfo);
Logger::log($request, $response, $additionalInfo)
}

Is it possible and how do I if so to pass a variable parameter to a Middleware in Laravel

I looking to set up a Middleware to check if the user is a subscriber to the page that they are on. I have tried a couple of options but both has required passing the URL to the Middleware.
The Route
Route::get('premium/{id}', function ($id) {
return $id;
})->middleware('subscribe:{$id}');
The Middleware
public function handle($request, Closure $next, $subscribe)
{
//dd($subscribe);
$c = DB::table('suscribes')->where('user_id', $request->user()->id)->where('subscribed_to', $subscribe)->count();
return $next($request);
}
The above $subscribe obviously returns a string of {$id} but have tried concatenating. Is there a better way?
As I am using Cashier and Stripe I have also tried setting up a new plan for each user. From docs.
public function handle($request, Closure $next)
{
if ($request->user() && ! $request->user()->subscribed('main')) {
// This user is not a paying customer...
return redirect('billing');
}
return $next($request);
}
But I still need to pass the variable to 'main'.
I'm not sure if I understand your requirement completely. But to get the value of some Requests route Parameter you can use $request->route('param-identifyer') function. Passing {$id} as parameter to the middleware is the wrong approach.
public function handle($request, Closure $next, $subscribe)
{
dd($request->route('id'));
$c = DB::table('suscribes')->where('user_id', $request->user()->id)->where('subscribed_to', $subscribe)->count();
return $next($request);
}

get request params in middleware handle

I'm going through HTTP Middleware manual. And have created a middleware "LogAll" and added it to $middleware array in Kernel.php.
Everything works fine, except I don't have request params (post or get) in the handle method of LogAll
public function handle($request, Closure $next)
{
var_dump($request->all());
return $next($request);
}
it prints an empty array. When calling a url that matches this route:
Route::get('/{id}', ['as' => 'profile', function($id) {
return $id;
}]);
Note that, I have added a route pattern in boot method that checks id to be numeric.
For retrieving route parameters you should use route():
public function handle($request, Closure $next)
{
echo $request->route('id');
return $next($request);
}

Resources