API route accessible for both: authenticated and unauthenticated
I have one API route (GET), which frontend calls in order to get data to render.
This route should be accessible for unauthenticated visitors, so they get the data (in such case, some fields may be null/false, taking care of that in the backend - using Auth::check()). If authenticated user calls that route, I need to run the request through auth:api middleware, so I get auth user, and serve him accordingly.
The issue:
If I use auth:api middleware on the route, it works for authenticated, but of course returns 401 for unauthenticated user.
If I don't use the middleware, it works fine for unauthenticated, but won't get user specific data for authenticated user.
What is the best approach to this scenario? So I can keep single route but make it work for both.
You could try checking if the HTTP_AUTHORIZATION key exists in $_SERVER to identify if the user is auth'd and then call the middleware. If the user is not auth'd you can omit the middleware and use the 'Auth::check()` in your logic.
public function __construct()
{
if (array_key_exists('HTTP_AUTHORIZATION', $_SERVER))
{
$this->middleware('auth:api');
}
}
//...
public function myFunction()
{
if (Auth::check())
{
// Code if user is auth'd
}
else
{
// Everyone else
}
}
If you use this approach, ensure you are not calling the middleware elsewhere, such as the route.