Skip to content

Instantly share code, notes, and snippets.

@koenhoeijmakers
Last active December 20, 2017 10:36
Show Gist options
  • Save koenhoeijmakers/c44a6b2ab4a3d243960903d93de5e532 to your computer and use it in GitHub Desktop.
Save koenhoeijmakers/c44a6b2ab4a3d243960903d93de5e532 to your computer and use it in GitHub Desktop.
Laravel Middleware that injects the access_token url parameter into the Authorization header.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Str;
/**
* Checks for the `access_token` parameter, and if exists, puts it in the Authorization header.
*/
class AccessTokenInjector
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->filled('access_token') && !$request->hasHeader('Authorization')) {
$request->headers->set('Authorization',
$this->getTokenFromRequest($request)
);
}
return $next($request);
}
/**
* Get the token from the request.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function getTokenFromRequest($request)
{
return Str::startsWith($token = $request->input('access_token'), 'Bearer ') ? $token : 'Bearer ' . $token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment