Skip to content

Instantly share code, notes, and snippets.

@xtrcode
Created April 26, 2024 09:51
Show Gist options
  • Save xtrcode/c305fd4eb77cf89a7085bdc1913c8d6c to your computer and use it in GitHub Desktop.
Save xtrcode/c305fd4eb77cf89a7085bdc1913c8d6c to your computer and use it in GitHub Desktop.
Laravel Sanctum authentication by request parameter
<?php
// app/Http/Middleware/AuthByGetParam.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AuthByGetParam
{
private Authenticate $auth;
public function __construct(Authenticate $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, ...$guards): Response
{
// transform get token to Authorization Bearer and pass request to sanctum
$request->headers->set('Authorization', 'Bearer ' . $request->get('token', ''));
// remove get token
$request->merge($request->except('token'));
return $this->auth->handle($request, $next, ...$guards);
}
}
// app/Providers/RouteServiceProvier.php
// add to boot method:
$this->aliasMiddleware('auth.get', AuthByGetParam::class);
// routes/web.php || routes/api.php
Route::middleware('auth.get:sanctum')->group(function (){
// place routes here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment