KrasMan's avatar

Problems with middleware and X-AUTH-ACCESS-TOKEN request header

I have a 3rd party api that I need to interact with that requires an access token in the request header. Using the guzzle client for the interface it's working fine by doing this directly, e.g.,

return http::withHeader("X-AUTH-ACCESS-TOKEN", $this->getXYZApiKey())
            ->post( ...

As my use expands on using this api, I figured I'd create a middleware routine to do directly:

<?php

namespace App\Http\Middleware;


use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
 
class XYZApiToken {
    /**
     * Handle an incoming request.
     *
     * @param \Closure(Request): (Response) $next
     */
    public function handle(Request $request, Closure $next): Response {
        $request->headers->set("X-AUTH-ACCESS-TOKEN", $this->getXYZToken());
        return $next($request);
    }

   private function getXYZToken(): string {
      // routine to get the token value
   }

and of course I hook it up to the api config in bootstrap:

->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'xyz_api_token' => XYZApiToken ::class
        ]);
    })

and with my api routes:

Route::prefix('v1/xyz/clients')->middleware(["xyz_api_token"])->group(function () {
    Route::post('/', [XYZClientController::class, "store"]);
   ...
});

I've confirmed that the wiring seems to all work, debugging clearly shows that middleware getting called and the header being added to the request header, but the actual call returns a 401 implying that in the final call the token is not available in the header. I've followed this as far as I'm aware of and can't figure out where this might be wrong. Any ideas?

0 likes
2 replies
Glukinho's avatar
Level 30

You're confusing concepts here.

Middleware is for interacting with incoming requests towards your app.

Http client fires outgoing requests from your app to external HTTP resources (such as API).

They are opposite of each other, and middleware can't be applied to HTTP client.

You may need to create a macro: https://laravel.com/docs/12.x/http-client#macros

// AppServiceProvider boot()
Http::macro('mysuperapi', function () {
	return Http::withHeaders([
		'X-AUTH-ACCESS-TOKEN' => '<token>',
	])->baseUrl('https://mysuperapi.com');
});

// usage
$response = Http::mysuperapi()->post($data);
KrasMan's avatar

I guess I was looking at this upside down. Too bad, but I'll look at the macro idea. Thanks!

Update: Yep, the macro approach was exactly what was needed. Works great! thanks.

Please or to participate in this conversation.