Home > Enterprise >  How to add Authorization header for API requests globally in Laravel
How to add Authorization header for API requests globally in Laravel

Time:12-20

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 App\Http\Middleware;

use Closure;

class BearerAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $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

CodePudding user response:

You can create a macro as mentioned in the document.Define the macro within the boot method of your application's App\Providers\AppServiceProvider class:

public function boot()
{
        Http::macro('github', function () {
            return Http::withToken('token')->baseUrl('https://github.com');
        });
}

and use like below

$response = Http::github()->get('/');

Ref :

Bearer Tokens

Macros

CodePudding user response:

the token should be a variable like so $response = Http::withHeaders(["Authorization" => "Bearer {$token}"])->get('httpa://example.com/api/v1/user');

  • Related