1

I have an api that used Dingo API. The current users therefore use a X-Api-Key header for authentication. I now want to switch to laravels implemented API system which requires an Authorization header.

Is it possible to tell laravel which header to use. Or preferrably: Is there a hook that I can use to modify the headers (e.g. copy the X-Api-Key header value into the Authorization header), before authentication takes place?

1
  • You can do this using Laravel's middleware. Commented Oct 11, 2017 at 17:56

1 Answer 1

2

You can create middleware like this:

<?php

namespace App\Http\Middleware;

use Closure;

class ModifyHeader extends BaseAuthorize
{
    public function handle($request, Closure $next)
    {
        if ($authorization = $request->header('X-Api-Key')) {
            $request->headers->set('Authorization', $authorization);
        }

        return $next($request);
    }
}

Then you need to add this middleware to $middlewareGroups or $routeMiddleware for example like this:

protected $middlewareGroups = [
    'api' => [
        // ... 
        \App\Http\Middleware\ModifyHeader::class,
    ],
    // ...
 ];

and then you should make sure that routes you want to make the change are in api middleware. Of course you can also create custom middleware group for this or apply this for selected routes.

Then for example if you add such route:

Route::group(['middleware' => 'api'], function () {
    Route::get('/test', function () {
        dd(request()->header('Authorization'));

    });
});

You should get the same value that is passed in X-Api-Key header.

Sign up to request clarification or add additional context in comments.

2 Comments

is it in the web or the api middlewareGroups ??
@Maraboc You are right, it's better to demonstrate this in api middleware for such usage although it depends on author application how exactly his middleware groups are organized

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.