skip to Main Content

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


  1. Chosen as BEST ANSWER

    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?


  2. You can create a macro as mentioned in the document.Define the macro within the boot method of your application’s AppProvidersAppServiceProvider 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

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search