When I send the header in such code the Api receives the token correctly :
$response = Http::withHeaders(["Authorization" => "Bearer token"])->get('httpa://example.com/api/v1/user');
I’m trying to do this globally so I don’t have to write withHeaders all the time on every request.
I created a middleware with this code and connected it to app/Http/kernel.php
namespace AppHttpMiddleware;
use Closure;
class BearerAuthMiddleware
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$request->headers->set('Authorization', 'Bearer token');
return $next($request);
}
} ```
but not work. The api does not receive this header
3
Answers
Okay, but here you also have to enter a macro for each request. No way to make the header globally appended to every request but under certain conditions? For example, that
$request->is('api/*')
and there is a token in the session?You can create a macro as mentioned in the document.Define the macro within the
boot
method of your application’sAppProvidersAppServiceProvider
class:and use like below
Ref :
Bearer Tokens
Macros
the token should be a variable like so
$response = Http::withHeaders(["Authorization" => "Bearer $token"])->get('httpa://example.com/api/v1/user');