Last active
December 20, 2017 10:36
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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