I have a custom api auth based on token. It is implemented using a middleware. I'd like to attach the logged in user to the request, so it will be available in the controller.
Here's what I tried in my middleware:
public function handle($request, Closure $next)
{
// Load api key
$api_key = ApiKey::where('api_key', $request->header('X-API-KEY'))
->with('user')
->first();
// Check if api key is valid
if (!$api_key) {
throw new HttpException(401, 'Invalid api key.');
}
// Append api key user to the request
$request->attributes->add(['api_user' => $api_key->user]);
// Proceed with the request
return $next($request);
}
Then in my controller, I've tried to retrieve the custom request attribute like this:
var_dump($request->get('api_user')); // returns 'null'
var_dump($request->attributes->get('api_user')); // returns 'null'
var_dump($request->api_user); // returns 'null'
I've also tried setting the api user to request like this also:
$request->attributes->set('api_user', $api_key->user);
$request->merge(['api_user' => $api_key->user]);
Still no luck.
Any ideas? or is this not possible?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire