I added middleware in the l5-swagger config and tried to print out the user object but it comes back null.
Is it possible to restrict specific or all API/documentation generated by swagger using roles and permissions defined inside of Laravel?
Edit Heres the Middleware, not much special here. IM just trying to check if the user exists here and it fails.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ApiDocumentationAuthCheck
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request):
(\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
dd(Auth()->user());
// if auth User allow access to API
return $next($request);
// else redirect to Login route with auto redirect back
}
}
In the l5-swagger config I have set the middleware like this
'middleware' => [
'api' => ['ApiDocumentationAuthCheck'],
'asset' => [],
'docs' => [],
'oauth2_callback' => [],
],
It is normal that your user returns null, wether you are logged in or not because the routes for l5-swagger documentation are handeled apart (meaning : they do not pass through web or api routes) which means that there are no pre-defined middlewares for them ( including the middlewares that handle the authentication)
To make it work you need to put all the middlewares you use for your routes : The default ones are either web or api
now you will have access to your Auth::user()
Note: the order here is important because the request passes through the middlewares in order and the default middleware are used to check the sessions and initialize them if necessary.
Example in my case I test if the user is not authenticated then I authenticate it: