nextapps-be / laravel-swagger-ui

Add Swagger UI to a Laravel application.
MIT License
160 stars 20 forks source link

Gate::define('viewSwaggerUI') does not work in staging environment #28

Closed tfmwl closed 7 months ago

tfmwl commented 7 months ago

Hi,

I can show the view (/openapi for me) in a local environment, but after deployment to stage (APP_ENV=staging in .env), I get 403 forbidden.

SwaggerUiServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class SwaggerUiServiceProvider extends ServiceProvider
{
    public function boot() : void
    {
        Gate::define('viewSwaggerUI', function () {
            return config('app.env') !== 'production';
        });
    }
}

config/swagger-ui.php

return [
    'path' => 'openapi',
    'middleware' => [
        'web',
        EnsureUserIsAuthorized::class,
    ],
    'file' => resource_path('openapi/api.json'),
    'modify_file' => true,
];

I double checked, that config('app.env') returns "staging", I also tried a simple return true, but it does not change the behaviour (403).

Any ideas would be greatly appreciated.

yinx commented 7 months ago

@tfmwl Since the 'EnsureUserIsAuthorized' middleware is being applied, could you try adding '$user' in the callback to the gate definition? Gate::define('viewSwaggerUI', function ($user) { return config('app.env') !== 'production'; });

tfmwl commented 7 months ago

Sorry for not responding earlier. Thanks for the idea, but it doesn't work, either. Also just returning true inside the Gate doesn't work - I have to completely remove EnsureUserIsAuthorized from config/swagger-ui.php in order for it to displays the page outside of a local context.

yinx commented 7 months ago

Only thing I can think of without seeing the codebase would be that maybe the SwaggerUiServiceProvider might not be included correctly in the app.php config file?

tfmwl commented 7 months ago

It is included under $providers.

'providers' => [
    /*
        * Application Service Providers...
        */
    . 
    .
    App\Providers\RouteServiceProvider::class,
    App\Providers\SwaggerUiServiceProvider::class,
    App\Providers\TelescopeServiceProvider::class,
    .   
    .
],
yinx commented 7 months ago

@tfmwl Sorry for the delayed response. I'm not really sure what is going wrong to be honest. The only other thing I would try is a slight variation to a previous suggestion. Gate::define('viewSwaggerUI', function ($user = null) { return config('app.env') !== 'production'; }); Making the $user default to null may be what is needed. But I'm not sure without a reproducing repo.

tfmwl commented 7 months ago

That did the trick. Would've expected for it to fire some exception or at least a notice.

Thanks!