DarkaOnLine / L5-Swagger

OpenApi or Swagger integration to Laravel
https://github.com/DarkaOnLine/L5-Swagger
MIT License
2.65k stars 396 forks source link

oauth2 + passport = Bearer <token> #57

Closed pedrofsn closed 6 years ago

pedrofsn commented 7 years ago

"Authorization" : "Bearer token213315454Sample"

Is it possible to handle this kind o header in "documentation-swagger"? If yes, how?

DarkaOnLine commented 7 years ago

It looks like Swagger UI not supporting this:

https://github.com/OAI/OpenAPI-Specification/issues/583 https://github.com/swagger-api/swagger-ui/pull/2234

joaoBeno commented 7 years ago

An way around this issue is specifying the auth as bellow:

 *     @SWG\SecurityScheme(
 *          securityDefinition="default",
 *          type="apiKey",
 *          in="header",
 *          name="Authorization"
 *      )

On the controller, add this:

 *     security={
 *         {
 *             "default": {}
 *         }
 *     }

Then you create a Middleware to append the Bearer, here is a sample:

class SwaggerFix
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (strpos($request->headers->get("Authorization"),"Bearer ") === false) {
            $request->headers->set("Authorization","Bearer ".$request->headers->get("Authorization"));
        }

        $response = $next($request);

        return $response;
    }
}

And then declare it on your Kernel.php:

// I placed it first so it runs before passport's middleware...
protected $routeMiddleware = [
    'swfix' => \App\Http\Middleware\SwaggerFix::class,
]

Now lets wait for Swagger v3 that is said to have oAuth2 support...

pedrofsn commented 7 years ago

Thanks @joaoBeno!

DarkaOnLine commented 7 years ago

Yes these variables are defined in config and passed into the view here:

https://github.com/DarkaOnLine/L5-Swagger/blob/master/src/Http/Controllers/ SwaggerController.php#L63-L71

On 23 March 2017 at 14:29, ratanakpek notifications@github.com wrote:

Hi! Everyone! I need help!

I am trying to install L5-swagger, so i follow the command from this L5-swagger https://github.com/DarkaOnLine/L5-Swagger but I got errored everytime that I try to open this view that show the swagger. It said that undefined variable: $urlToDocs, $highlightThreshold,... and another variable. I commented the variable error already...

for my question is that "How can I give the value to these variable?" in config/l5-swagger file?

`<?php

if (app()->environment() != 'testing') { header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST'); header("Access-Control-Allow-Headers: X-Requested-With"); }

?>

{{config('l5-swagger.api.title')}} swagger Explore <#m_-324956319607622765_m_1126979693123509463_> ` β€” You are receiving this because you commented. Reply to this email directly, view it on GitHub , or mute the thread .
ratanakpek commented 7 years ago

Thanks Bro!

pamaleona-navagis commented 7 years ago

where does the middleware should be called?

joaoBeno commented 7 years ago

@pamaleona-navagis if you place this on your Kernel.php:

    // I placed it first so it runs before passport's middleware...
    protected $routeMiddleware = [
        'swfix' => \App\Http\Middleware\SwaggerFix::class,
    ]

It will run on all requests... If they don't have the bearer header, it will get it from the DB and append it to the request, before Passport handle the request...

Ps.: you need to past just the "swfix" line as the first item of the $routeMiddleware array...

pamaleona-navagis commented 7 years ago

I tried putting it on the forst line on the route middleware but unfortunately it doesn't work.

On Nov 9, 2017 7:40 AM, "joaoBeno" notifications@github.com wrote:

@pamaleona-navagis https://github.com/pamaleona-navagis if you place this on your Kernel.php: // I placed it first so it runs before passport's middleware... protected $routeMiddleware = [ 'swfix' => \App\Http\Middleware\SwaggerFix::class, ]

It will run on all requests... If they don't have the bearer header, it will get it from the DB and append it to the request, before Passport handle the request...

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/DarkaOnLine/L5-Swagger/issues/57#issuecomment-342998776, or mute the thread https://github.com/notifications/unsubscribe-auth/AdjxKfYXGFNdod8AJ6W6meT7xE6lfk61ks5s0jwCgaJpZM4MJGgj .

joaoBeno commented 7 years ago

@pamaleona-navagis, please post your kernel.php on a gist, and post the link here, so I can give you more support without notifying other people... πŸ‘

pamaleona-navagis commented 7 years ago

Here's my Kernel.php

https://gist.github.com/pamaleona-navagis/5010be66f1594fb98cea17d3098605af

On Thu, Nov 9, 2017 at 5:52 PM, joaoBeno notifications@github.com wrote:

@pamaleona-navagis https://github.com/pamaleona-navagis, please post your kernel.php on a gist, and post the link here, so I can give you more support without notifying other people... πŸ‘

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/DarkaOnLine/L5-Swagger/issues/57#issuecomment-343103252, or mute the thread https://github.com/notifications/unsubscribe-auth/AdjxKRGa0jd9Pkd_FwJnwVlgObdR10Ljks5s0stkgaJpZM4MJGgj .

yajra commented 6 years ago

Sharing my solution in case it might help.

This is I how made it to work with Passport using password grant. No need for middleware since latest version uses Swagger UI v3.

Note: this snippets assumes that you already completed the passport setup.

  1. Add passport security on swagger config

        'passport' => [ // Unique name of security
            'type' => 'oauth2', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
            'description' => 'Laravel passport oauth2 security.',
            'flow' => 'password', // The flow used by the OAuth2 security scheme. Valid values are "implicit", "password", "application" or "accessCode".
            'tokenUrl' => config('app.url') . '/oauth/token', // The authorization URL to be used for (password/application/accessCode)
            'scopes' => []
        ],
  2. Add swagger security scheme Duplicate of step 1, can be skipped as per @DarkaOnLine

 * @SWG\SecurityScheme(
 *   securityDefinition="passport",
 *   type="oauth2",
 *   tokenUrl="/oauth/token",
 *   flow="password",
 *   scopes={}
 * )
  1. Include "passport" on your request security:
 * @SWG\Get(
 *   path="/api/user",
 *   tags={"user"},
 *   security={
 *     {"passport": {}},
 *   },
 *   summary="Get user",
 *   @SWG\Response(
 *     response=200,
 *     description="Logged in user info"
 *   )
 * )
  1. Generate Docs

  2. Authorized the request using the swagger interface and bearer tokens should be added now on secured request.

    screen shot 2017-12-07 at 2 17 36 pm

Request

screen shot 2017-12-07 at 2 17 15 pm
DarkaOnLine commented 6 years ago

@yajra thanks for sharing.

But I think steps 1 and 2 duplicate each other. You need to use only one of them. Because security definitions in the config file will be generated and appended to the final swagger documentation json file: https://github.com/DarkaOnLine/L5-Swagger/blob/master/src/Generator.php#L46

yajra commented 6 years ago

@DarkaOnLine thanks for pointing that out. Will update my answer and my code. πŸ‘

rwngallego commented 6 years ago

Is there a way to keep the user login even if I reload the Swagger UI? It's loosing the authentication

akalongman commented 6 years ago

@yajra is possible to set default values for client_id or etc. inputs?

am0nshi commented 6 years ago

@DarkaOnLine joining to last questions

DarkaOnLine commented 6 years ago

Please see @joseph-montanez suggestions here: https://github.com/DarkaOnLine/L5-Swagger/issues/120

amitgaur208 commented 6 years ago

@yajra But when we add security to any Api then should not send response without authorization

kranthi610 commented 6 years ago

this is what I did after reading the API doc and it worked for me * @OAS\SecurityScheme(

//////////////////////////////////////

security={

kevincobain2000 commented 6 years ago

Passport annotation is good but when you have your own middleware then how about setting it to the interceptor and adding respective middlewares to the l5-swagger config file?

my-project/resources/views/vendor/l5-swagger/index.blade.php

    requestInterceptor: function() {
      this.headers['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
      this.headers['Authorization'] = 'Bearer ' + '{{ Cookie::get("jwt-token") }}'
      return this;
    },
oyepez003 commented 6 years ago

With latest version of l5-swagger:

Follow the Passport Instalation/Configuration

l5-swagger.php

'security' => [
       /* Open API 3.0 support*/
        'passport' => [ // Unique name of security
            'type'        => 'oauth2', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
            'description' => 'Laravel passport oauth2 security.',
            'in'          => 'header',
            'scheme'      => 'https',
            'flows'       => [
                "password" => [
                    "authorizationUrl" => config('app.url') . '/oauth/authorize',
                    "tokenUrl"         => config('app.url') . '/oauth/token',
                    "refreshUrl"       => config('app.url') . '/token/refresh',
                    "scopes"           => []
                ],
            ],
        ],
],

In your secured controller:

/**
     * @OA\Get(
     *   path="/mySecuredEndpoint",
     *   summary="Secured with passport",
     *   description="Secured with passport",
     *   tags={"Passport Security"},
     *   security={{"passport": {"*"}}},
     *   @OA\Response(
     *     @OA\MediaType(mediaType="application/json"),
     *     response=200,
     *     description="My Response"
     *   ),
     *   @OA\Response(
     *     @OA\MediaType(mediaType="application/json"),
     *     response="default",
     *     description="an ""unexpected"" error"
     *   )
     * )

And done... Should be work.

hoangnkvti commented 6 years ago

image

I followed @oyepez003 and used default passport setting from l5-swagger.php file but don't see password in popup?

How can I fix my problem?

ssheduardo commented 6 years ago

Hi, I follow all steps for uses oauth2 + bearer, but some reason when called a method ever see the called into curl but not attach Bearer only the X-CSRF-TOKEN.

We uses Client Credentials Grant Tokens

swagger-error-1

swagger-error-2

This is my route:

Route::get('demo', 'ShippingController@demo')->name('api.v1.demo');

My RouteServiceProvider

    protected function mapClientCredentialRoutes()
    {
        Route::middleware('client_credentials')
             ->namespace($this->namespace)
             ->group(base_path('routes/client_credentials.php'));
    }

In Controller.php add

/**
 * @OA\Info(
 *     description="Shipping API",
 *     version="1.0.0",
 *     title="Demo shipping",
 *     termsOfService="http://swagger.io/terms/",
 *     @OA\Contact(
 *         email="info@demo.com"
 *     ),
 *     @OA\License(
 *         name="Apache 2.0",
 *         url="http://www.apache.org/licenses/LICENSE-2.0.html"
 *     )
 * )
 */
/**
 * @OA\Tag(
 *     name="shipping",
 *     description="",
 * )
 * @OA\Server(
 *     description="SwaggerHUB API Mocking",
 *     url="http://api-demo.local"
 * )
 */
/**
 * @OA\SecurityScheme(
 *     @OA\Flow(
 *         flow="clientCredentials",
 *         tokenUrl="oauth/token",
 *         scopes={}
 *     ),
 *     securityScheme="oauth2",
 *     in="header",
 *     type="oauth2",
 *     description="Oauth2 security",
 *     name="oauth2",
 *     scheme="http",
 *     bearerFormat="bearer",
 * )
 */
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

And ShippingController

....
....
/**
     * @OA\Schema(
     *   schema="myname",
     *   type="string",
     *   description="Return a name"
     * )
     */

    /**
     * @OA\Get(
     *
     *   path="/api/v1/demo",
     *   summary="Get name",
     *   @OA\Response(
     *     response=200,
     *     description="successful operation",
     *     @OA\JsonContent(ref="#/components/schemas/myname"),
     *   )
     * )
     */

    public function demo()
    {
        return ['name' => 'Peter'];
    }
....
....

kernel.php

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
        'client_credentials' => [
            CheckClientCredentials::class,
            'throttle:60,1',
            'bindings',
        ],

    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'client' => CheckClientCredentials::class,
    ];

Where are the error?

Some idea @oyepez003 , @yajra @kranthi610, etc?

oyepez003 commented 6 years ago

@ssheduardo Check the passport option in the config/l5-swagger.php

'passport' => [
  ...
  'in'          => 'header',
  ...
]
ssheduardo commented 6 years ago

@oyepez003 Change in l5-swagger and done? Con solo cambiar eso ya estarΓ­a, no tengo que modificar en otro lado?

kranthi610 commented 6 years ago

@OA\SecurityScheme(

this should help

Hi, I follow all steps for uses oauth2 + bearer, but some reason when called a method ever see the called into curl but not attach Bearer only the X-CSRF-TOKEN.

We uses Client Credentials Grant Tokens

swagger-error-1

swagger-error-2

This is my route:

Route::get('demo', 'ShippingController@demo')->name('api.v1.demo');

My RouteServiceProvider

    protected function mapClientCredentialRoutes()
    {
        Route::middleware('client_credentials')
             ->namespace($this->namespace)
             ->group(base_path('routes/client_credentials.php'));
    }

In Controller.php add

/**
 * @OA\Info(
 *     description="Shipping API",
 *     version="1.0.0",
 *     title="Demo shipping",
 *     termsOfService="http://swagger.io/terms/",
 *     @OA\Contact(
 *         email="info@demo.com"
 *     ),
 *     @OA\License(
 *         name="Apache 2.0",
 *         url="http://www.apache.org/licenses/LICENSE-2.0.html"
 *     )
 * )
 */
/**
 * @OA\Tag(
 *     name="shipping",
 *     description="",
 * )
 * @OA\Server(
 *     description="SwaggerHUB API Mocking",
 *     url="http://api-demo.local"
 * )
 */
/**
 * @OA\SecurityScheme(
 *     @OA\Flow(
 *         flow="clientCredentials",
 *         tokenUrl="oauth/token",
 *         scopes={}
 *     ),
 *     securityScheme="oauth2",
 *     in="header",
 *     type="oauth2",
 *     description="Oauth2 security",
 *     name="oauth2",
 *     scheme="http",
 *     bearerFormat="bearer",
 * )
 */
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

And ShippingController

....
....
/**
     * @OA\Schema(
     *   schema="myname",
     *   type="string",
     *   description="Return a name"
     * )
     */

    /**
     * @OA\Get(
     *
     *   path="/api/v1/demo",
     *   summary="Get name",
     *   @OA\Response(
     *     response=200,
     *     description="successful operation",
     *     @OA\JsonContent(ref="#/components/schemas/myname"),
     *   )
     * )
     */

    public function demo()
    {
        return ['name' => 'Peter'];
    }
....
....

kernel.php

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
        'client_credentials' => [
            CheckClientCredentials::class,
            'throttle:60,1',
            'bindings',
        ],

    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'client' => CheckClientCredentials::class,
    ];

Where are the error?

Some idea @oyepez003 , @yajra @kranthi610, etc?

ssheduardo commented 6 years ago

After added the changes, this is the response

image

And this

image

/**
 * @OA\SecurityScheme(
 *     @OA\Flow(
 *         flow="clientCredentials",
 *         tokenUrl="oauth/token",
 *         scopes={}
 *     ),
 *     securityScheme="bearerAuth",
 *     in="header",
 *     type="http",
 *     description="Oauth2 security",
 *     name="oauth2",
 *     scheme="bearer",
 *     bearerFormat="JWT",
 * )
 */

Why not set the Bearer??? @kranthi610


@OA\SecurityScheme(

  • securityScheme="bearerAuth",
  • type="http",
  • scheme="bearer",
  • bearerFormat="JWT",
  • )

this should help

Hi, I follow all steps for uses oauth2 + bearer, but some reason when called a method ever see the called into curl but not attach Bearer only the X-CSRF-TOKEN.

We uses Client Credentials Grant Tokens

swagger-error-1 swagger-error-2 This is my route: Route::get('demo', 'ShippingController@demo')->name('api.v1.demo'); My RouteServiceProvider

    protected function mapClientCredentialRoutes()
    {
        Route::middleware('client_credentials')
             ->namespace($this->namespace)
             ->group(base_path('routes/client_credentials.php'));
    }

In Controller.php add

/**
 * @OA\Info(
 *     description="Shipping API",
 *     version="1.0.0",
 *     title="Demo shipping",
 *     termsOfService="http://swagger.io/terms/",
 *     @OA\Contact(
 *         email="info@demo.com"
 *     ),
 *     @OA\License(
 *         name="Apache 2.0",
 *         url="http://www.apache.org/licenses/LICENSE-2.0.html"
 *     )
 * )
 */
/**
 * @OA\Tag(
 *     name="shipping",
 *     description="",
 * )
 * @OA\Server(
 *     description="SwaggerHUB API Mocking",
 *     url="http://api-demo.local"
 * )
 */
/**
 * @OA\SecurityScheme(
 *     @OA\Flow(
 *         flow="clientCredentials",
 *         tokenUrl="oauth/token",
 *         scopes={}
 *     ),
 *     securityScheme="oauth2",
 *     in="header",
 *     type="oauth2",
 *     description="Oauth2 security",
 *     name="oauth2",
 *     scheme="http",
 *     bearerFormat="bearer",
 * )
 */
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

And ShippingController

....
....
/**
     * @OA\Schema(
     *   schema="myname",
     *   type="string",
     *   description="Return a name"
     * )
     */

    /**
     * @OA\Get(
     *
     *   path="/api/v1/demo",
     *   summary="Get name",
     *   @OA\Response(
     *     response=200,
     *     description="successful operation",
     *     @OA\JsonContent(ref="#/components/schemas/myname"),
     *   )
     * )
     */

    public function demo()
    {
        return ['name' => 'Peter'];
    }
....
....

kernel.php

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
        'client_credentials' => [
            CheckClientCredentials::class,
            'throttle:60,1',
            'bindings',
        ],

    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'client' => CheckClientCredentials::class,
    ];

Where are the error? Some idea @oyepez003 , @yajra @kranthi610, etc?

kranthi610 commented 6 years ago

After added the changes, this is the response

image

And this

image

/**
 * @OA\SecurityScheme(
 *     @OA\Flow(
 *         flow="clientCredentials",
 *         tokenUrl="oauth/token",
 *         scopes={}
 *     ),
 *     securityScheme="bearerAuth",
 *     in="header",
 *     type="http",
 *     description="Oauth2 security",
 *     name="oauth2",
 *     scheme="bearer",
 *     bearerFormat="JWT",
 * )
 */

Why not set the Bearer??? @kranthi610

@OA\SecurityScheme(

  • securityScheme="bearerAuth",
  • type="http",
  • scheme="bearer",
  • bearerFormat="JWT",
  • )

this should help

Hi, I follow all steps for uses oauth2 + bearer, but some reason when called a method ever see the called into curl but not attach Bearer only the X-CSRF-TOKEN.

We uses Client Credentials Grant Tokens

swagger-error-1 swagger-error-2 This is my route: Route::get('demo', 'ShippingController@demo')->name('api.v1.demo'); My RouteServiceProvider

    protected function mapClientCredentialRoutes()
    {
        Route::middleware('client_credentials')
             ->namespace($this->namespace)
             ->group(base_path('routes/client_credentials.php'));
    }

In Controller.php add

/**
 * @OA\Info(
 *     description="Shipping API",
 *     version="1.0.0",
 *     title="Demo shipping",
 *     termsOfService="http://swagger.io/terms/",
 *     @OA\Contact(
 *         email="info@demo.com"
 *     ),
 *     @OA\License(
 *         name="Apache 2.0",
 *         url="http://www.apache.org/licenses/LICENSE-2.0.html"
 *     )
 * )
 */
/**
 * @OA\Tag(
 *     name="shipping",
 *     description="",
 * )
 * @OA\Server(
 *     description="SwaggerHUB API Mocking",
 *     url="http://api-demo.local"
 * )
 */
/**
 * @OA\SecurityScheme(
 *     @OA\Flow(
 *         flow="clientCredentials",
 *         tokenUrl="oauth/token",
 *         scopes={}
 *     ),
 *     securityScheme="oauth2",
 *     in="header",
 *     type="oauth2",
 *     description="Oauth2 security",
 *     name="oauth2",
 *     scheme="http",
 *     bearerFormat="bearer",
 * )
 */
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

And ShippingController

....
....
/**
     * @OA\Schema(
     *   schema="myname",
     *   type="string",
     *   description="Return a name"
     * )
     */

    /**
     * @OA\Get(
     *
     *   path="/api/v1/demo",
     *   summary="Get name",
     *   @OA\Response(
     *     response=200,
     *     description="successful operation",
     *     @OA\JsonContent(ref="#/components/schemas/myname"),
     *   )
     * )
     */

    public function demo()
    {
        return ['name' => 'Peter'];
    }
....
....

kernel.php

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
        'client_credentials' => [
            CheckClientCredentials::class,
            'throttle:60,1',
            'bindings',
        ],

    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'client' => CheckClientCredentials::class,
    ];

Where are the error? Some idea @oyepez003 , @yajra @kranthi610, etc?

Check the security scheme...I'm using bearer scheme.this is how my security definiton looks /* schemes={"http,https"},

*security={

Lemme know if this helps

ssheduardo commented 6 years ago

*security={

  •     {"bearerAuth": {}}
  •   }

*)

Where put this code?

*security={

      {"bearerAuth": {}}
    }
*)

Please attached a screenshot.

kranthi610 commented 6 years ago

*security={

  •     {"bearerAuth": {}}
  •   }

*)

Where put this code?

*security={

      {"bearerAuth": {}}
    }
*)

Please attached a screenshot.

Top of your controller ..Take a look on this pet controller example https://github.com/zircote/swagger-php/blob/9e8aeca0618c50a1b70f14962f84eeec5e93e4e2/Examples/petstore-3.0/controllers/Pet.php#L192

ssheduardo commented 6 years ago

{"bearerAuth": {}}

Perfect, I got it!

image

class CustomController extends Controller
{
    /**
     * @OA\Schema(
     *   schema="myname",
     *   type="string",
     *   description="Return a name"
     * )
     */

    /**
     * @OA\Get(
     *
     *   path="/api/v1/demo",
     *   summary="Get name",
     *   @OA\Response(
     *     response=200,
     *     description="successful operation",
     *     @OA\JsonContent(ref="#/components/schemas/myname"),
     *   ),
     *     security={
     *         {"bearerAuth": {}}
     *     }
     * )
     */
    public function demo()
    {
        return ['name' => 'Peter', 'time' => Carbon::now()];
    }
}

Thanks you @kranthi610

kranthi610 commented 6 years ago

{"bearerAuth": {}}

Perfect, I got it!

image

class CustomController extends Controller
{
    /**
     * @OA\Schema(
     *   schema="myname",
     *   type="string",
     *   description="Return a name"
     * )
     */

    /**
     * @OA\Get(
     *
     *   path="/api/v1/demo",
     *   summary="Get name",
     *   @OA\Response(
     *     response=200,
     *     description="successful operation",
     *     @OA\JsonContent(ref="#/components/schemas/myname"),
     *   ),
     *     security={
     *         {"bearerAuth": {}}
     *     }
     * )
     */
    public function demo()
    {
        return ['name' => 'Peter', 'time' => Carbon::now()];
    }
}

Thanks you @kranthi610 cool :)

ssheduardo commented 6 years ago

Why not anyone create a tutorial this?

ssheduardo commented 6 years ago

This is a last question. How to remove -H "X-CSRF-TOKEN: " ??

image

eleftrik commented 5 years ago

Is there a way to keep the user logged in, after refreshing Swagger UI page? I got it working, but every time I reload the page I have to insert again username, password, client_id and client_secret. Thanks

eleftrik commented 5 years ago

Is there a way to keep the user logged in, after refreshing Swagger UI page?

I reply to myself: yes, there is. Found this: https://github.com/DarkaOnLine/L5-Swagger/issues/120#issuecomment-369914262

thangho98 commented 5 years ago

image

Need your help? I cannot authorizations swagger when loggin by email, password using config security passport

lunwhl commented 5 years ago

@Doublefree9

image

Need your help? I cannot authorizations swagger when loggin by email, password using config security passport

You can use this

  • @SWG\SecurityScheme(
  • securityDefinition="MyHeaderAuthentication",
  • type="apiKey",
  • in="header",
  • name="Authorization"
  • ),

The apiKey is the Bearer token. You build a login api, copy the token into "apiKey" with "Bearer THE TOKEN U COPY"

ihamzehald commented 4 years ago

Adding a full example for a get request:

In top of your main controller add this:

/**

On top of your get request add this :

/**
 * Get the authenticated User.
 * @return \Illuminate\Http\JsonResponse
 *
 * Swagger UI documentation (OA)
 *
 * @OA\Get(
 *   path="/user/auth/jwt/me",
 *   tags={"User"},
 *   summary="Get the authenticated User",
 *   description="Get the authenticated User",
 *   operationId="jwtMe",
 *  @OA\Response(
 *         response="200",
 *         description="ok",
 *         content={
 *             @OA\MediaType(
 *                 mediaType="application/json",
 *                 @OA\Schema(ref="#/components/schemas/User")
 *              )
 *         }
 *     ),
 *   @OA\Response(response="401",description="Unauthorized"),
 *  security={
 *         {"bearerAuth": {}}
 *     }
 * )
 */

Here is a sample of User schema, add it on top of your model.

/**

praj commented 4 years ago

If you notice your requests just time out with Laravel passport, then make sure you have this in your controller methods (requests) tags after setting up Laravel Passport as a security type in your l5-swagger.php config file.

security={{"passport": {"*"}}},

Initially I was using this (without the asterisk):

security={{"passport": {""}}},
K2ouMais commented 4 years ago

I cant get this to work...

I have this in my Controller.php

/**
 * @OA\Info(
 *      version="1.0.0",
 *      title="My API",
 *      description="This is a test",
 * )
 *
 * @OA\Tag(
 *     name="Addresses",
 *     description="Handle your order addresses.",
 * )
 *
* @OA\SecurityScheme(
*      securityScheme="bearerAuth",
*      type="http",
*      scheme="bearer",
*  )
*/

Now I have this on my AddressesController.php:

    /**
     * @OA\Get(
     *      path="/addresses/",
     *      operationId="showAddresses",
     *      tags={"Addresses"},
     *      summary="Show all your addresses.",
     *      description="Show all your addresses.",
     *      @OA\Response(response=200, description="OK"),
     *      @OA\Response(response=401, description="Unauthorized."),
     *      security={
     *         {"bearerAuth": {}}
     *      }
     *     )
     */

This is the cURL:

curl -X GET "http://lei-api-swagger.test/api/addresses/" -H "accept: */*" -H "Authorization: Bearer 456987sdfsdeasaASDASD" -H "X-CSRF-TOKEN: "

It works without a problem in Postman...

Everytime I hit that endpoint I get a 401 Unauthorised.

What am I doing wrong?

How can I pass the "Accept" header?

How can I take the "X-CSRF-TOKEN:" out?

Thanks in advance

kranthi610 commented 4 years ago

I cant get this to work...

I have this in my Controller.php

/**
 * @OA\Info(
 *      version="1.0.0",
 *      title="My API",
 *      description="This is a test",
 * )
 *
 * @OA\Tag(
 *     name="Addresses",
 *     description="Handle your order addresses.",
 * )
 *
* @OA\SecurityScheme(
*      securityScheme="bearerAuth",
*      type="http",
*      scheme="bearer",
*  )
*/

Now I have this on my AddressesController.php:

    /**
     * @OA\Get(
     *      path="/addresses/",
     *      operationId="showAddresses",
     *      tags={"Addresses"},
     *      summary="Show all your addresses.",
     *      description="Show all your addresses.",
     *      @OA\Response(response=200, description="OK"),
     *      @OA\Response(response=401, description="Unauthorized."),
     *      security={
     *         {"bearerAuth": {}}
     *      }
     *     )
     */

This is the cURL:

curl -X GET "http://lei-api-swagger.test/api/addresses/" -H "accept: */*" -H "Authorization: Bearer 456987sdfsdeasaASDASD" -H "X-CSRF-TOKEN: "

It works without a problem in Postman...

Everytime I hit that endpoint I get a 401 Unauthorised.

What am I doing wrong?

How can I pass the "Accept" header?

How can I take the "X-CSRF-TOKEN:" out?

Thanks in advance

Change your security definition to this and try @OA\SecurityScheme(

K2ouMais commented 4 years ago

@kranthi610 Still doesnt work...

kranthi610 commented 4 years ago

@kranthi610 Still doesnt work...

share me the swagger UI for API

K2ouMais commented 4 years ago

I was because of the "Accept" header.

Please I need to know how to change the "Accept" header?

It is everytime */* but I need it to be application/json.

And I also need to know how to take out the "X-CSRF-TOKEN" header??

It is a shame, that I cant find any documentation for this 2 things.

@DarkaOnLine Could you please help here?? Thank you in advance

kranthi610 commented 4 years ago

Mine looks like this.. in my Adress controller...

*@OA\Response(

this is how you do in base controller

/* schemes={"http,https"},

K2ouMais commented 4 years ago

I already said that I got it to work, but I had to change a Middleware where I only accept the accept header of application/json.

It seems there is a problem with the request headers.

It sends Accept */* and the in my case useless X-CSRF-TOKEN that by the way is empty.

sevaldes commented 4 years ago

I already said that I got it to work, but I had to change a Middleware where I only accept the accept header of application/json.

It seems there is a problem with the request headers.

It sends Accept */* and the in my case useless X-CSRF-TOKEN that by the way is empty.

Hi dude, i was the same problem. Just deleting the interceptor function it works to me. Good luck!.

/*
requestInterceptor: function() {
        if (this.headers) {
            this.headers['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
        }

      return this;
},
*/
buildsomethingdifferent commented 3 years ago

Simple solution guys. go to index.blade.php file and find method requestInterceptor(); and replace with below code.

requestInterceptor: function(request) {
   request.headers['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
   request.headers['Authorization'] = 'Bearer ' + request.headers['Authorization'];
  return request;
}

no need to create any middleware. securityScheme Passport in Your l5-swagger.php file should be like this

 'passport' => [ // Unique name of security
                'type' => 'apiKey', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
                'description' => 'Laravel passport security.',
                'in' => 'header',
                'name' => 'Authorization',
                'scheme' => 'https',
                'flows' => [
                    "password" => [
                        "authorizationUrl" => config('app.url') . '/oauth/authorize',
                        "tokenUrl" => config('app.url') . '/oauth/token',
                        "refreshUrl" => config('app.url') . 'oauth/token/refresh',
                        "scopes" => []
                    ],
                ],
            ],