How do I restrict l5-swagger documentation to users based on roles and permissions?

2.5k Views Asked by At

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' => [],
        ],
1

There are 1 best solutions below

0
houssem On

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

    'middleware' => [
        'api' => [
            'api', // or 'web' if you are using web routes
            'ApiDocumentationAuthCheck',
        ],
        'asset' => [],
        'docs' => [],
        'oauth2_callback' => [],
    ],

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:

        $user = Auth::user(); //get authenticated user
        if (empty($user)) { //if no user is authenticated then manually log him
            return response()->redirectTo("/api/login?intended=/api/documentation");
        }
        if ($user->role == 'admin') {
            throw new UnauthorizedException("You do not have the necessary access to perform this action (Documentation Access).");
        }