I'm having a middleware problem when I run my app in GAE. This is responsible for performing a basic validation in queries to my api. What it basically does is take an "api_token" that is sent in the header of each query and checks if it corresponds to any user. If it is NOT valid, it returns a 401 code with a text "Not authorized". The strange thing is that it works correctly locally but on the server it always returns 401. Analyzing the behavior a bit, apparently the token query to the db does not return any user. Below I leave some tests that I did, by which I show that the user exists, the token is being sent in the header and corresponds to the same one stored in the db.
Middleware:
public function handle($request, Closure $next)
{
$user = User::where('api_token', $request->header('api_token'))->first();
if ($user === null) {
return response()->json ('No autorizado', 401);
}
return $next($request);
}
Apparently $user is always null.
Request capture from the browser:
Capture request and response from Postman:
User capture with its corresponding api_token in the DB:
Important: There is NO connection problem with the DB, if I disable the middleware for the routes the queries work perfectly. Thank you very much in advance, greetings.
I managed to solve it... with a lot of patience and after several tests I managed to detect the error.
First I modified my middleware by incorporating
dd($request->header('api_token'));
and made a new deploy. With this I was able to visualize that this code for some reason was not working in GAE and always returned Null even if it sent the "api_token" header. I thought the header() method might be responsible so I modified my middleware again by replacing the above withdd($request->headers);
and made a new deploy. At this point, I was able to determine that even though I was sending my header from both Postman and the browser, it was not reaching my server, something along the way was eliminating or blocking it! After this, in a moment of enlightenment, I realized that all Laravel custom headers are issued with certain conventions. Words separated by "-" and not by "_" as I did, on the other hand were sent in upper case. So I did a test, replace “ api_token ” with “ API-TOKEN ” in my Postman query and Voila! Now my server received said header. So I made the relevant adjustments in the middleware too and problem solved!I hope it saves someone the headache. Cheers!