Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

oauth2 + passport = Bearer <token> #57

Closed
pedrofsn opened this issue Feb 22, 2017 · 49 comments
Closed

oauth2 + passport = Bearer <token> #57

pedrofsn opened this issue Feb 22, 2017 · 49 comments
Labels

Comments

@pedrofsn
Copy link

"Authorization" : "Bearer token213315454Sample"

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

@DarkaOnLine
Copy link
Owner

It looks like Swagger UI not supporting this:

OAI/OpenAPI-Specification#583
swagger-api/swagger-ui#2234

@joaoBeno
Copy link

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
Copy link
Author

Thanks @joaoBeno!

@DarkaOnLine
Copy link
Owner

DarkaOnLine commented Mar 23, 2017 via email

@ratanakpek
Copy link

Thanks Bro!

@pamaleona-navagis
Copy link

pamaleona-navagis commented Nov 8, 2017

where does the middleware should be called?

@joaoBeno
Copy link

joaoBeno commented Nov 8, 2017

@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
Copy link

pamaleona-navagis commented Nov 9, 2017 via email

@joaoBeno
Copy link

joaoBeno commented Nov 9, 2017

@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
Copy link

pamaleona-navagis commented Nov 9, 2017 via email

@yajra
Copy link

yajra commented Dec 7, 2017

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' => []
        ],
  1. 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
Copy link
Owner

@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
Copy link

yajra commented Dec 7, 2017

@DarkaOnLine thanks for pointing that out. Will update my answer and my code. 👍

@rwngallego
Copy link

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

@akalongman
Copy link

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

@am0nshi
Copy link

am0nshi commented Apr 5, 2018

@DarkaOnLine joining to last questions

@DarkaOnLine
Copy link
Owner

Please see @joseph-montanez suggestions here: #120

@amitgaur208
Copy link

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

@kranthi610
Copy link

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

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

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

security={

  •       {"bearerAuth": {}}
    
  •     }
    

@kevincobain2000
Copy link

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
Copy link

oyepez003 commented Sep 10, 2018

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"
     *   )
     * )
  • Regenerate the docs.
  • Create a Personal client with Passport (Artisan CLI).
  • Refresh the Swagger UI and set the User, Password, Cient ID, Client Secret, Scope (if it's required).

And done... Should be work.

@hoangnkvti
Copy link

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
Copy link

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
Copy link

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

'passport' => [
  ...
  'in'          => 'header',
  ...
]

@ssheduardo
Copy link

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

@kranthi610
Copy link

@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?

@ssheduardo
Copy link

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
Copy link

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"},

  • @OA\Info(
  • description="LIve API",
    
  • version="1.0.0",
    
  • title="Live API",
    
  • ),
  • @OA\Tag(
  • name="Clubs",
    
  • description="Everything about Pets",
    
  • ),
  • @OA\Server(
  • description="SwaggerHUB API Mocking",
    
  • url="http://dev.testapp.org"
    
  • )
  • @OA\SecurityScheme(
  • securityScheme="bearerAuth",
    
  • type="http",
    
  • scheme="bearer",
    
  • bearerFormat="JWT",
    
  • )
    */

*security={

  •       {"bearerAuth": {}}
    
  •     }
    

*)

Lemme know if this helps

@ssheduardo
Copy link

*security={

  •       {"bearerAuth": {}}
    
  •     }
    

*)

Where put this code?

*security={

      {"bearerAuth": {}}
    }
*)

Please attached a screenshot.

@kranthi610
Copy link

*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
Copy link

{"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
Copy link

{"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
Copy link

Why not anyone create a tutorial this?

@ssheduardo
Copy link

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

image

@eleftrik
Copy link

eleftrik commented Jun 28, 2019

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
Copy link

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

I reply to myself: yes, there is. Found this: #120 (comment)

@thangho98
Copy link

thangho98 commented Aug 27, 2019

image

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

@lunwhl
Copy link

lunwhl commented Sep 23, 2019

@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
Copy link

Adding a full example for a get request:

In top of your main controller add this:

/**

  • @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",
    
  • )
    */

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.

/**

  • @OA\Schema(@OA\Xml(name="User"))
  • @OA\Property(
  • property="id",
  • type="string",
  • description="User ID"
  • )
  • @OA\Property(
  • property="name",
  • type="string",
  • description="User name"
  • )
  • @OA\Property(
  • property="email",
  • type="string",
  • description="User email"
  • )
  • @OA\Property(
  • property="email_verified_at",
  • type="string",
  • description="Email verified at"
  • )
  • @OA\Property(
  • property="created_at",
  • type="string",
  • description="Created at"
  • )
    • @OA\Property(
  • property="updated_at",
  • type="string",
  • description="Updated at"
  • )
    • @OA\Property(
  • property="api_token",
  • type="string",
  • description="Api token (used for token auth)"
  • )
    */

@praj
Copy link

praj commented May 5, 2020

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
Copy link

K2ouMais commented May 18, 2020

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
Copy link

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(

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

@K2ouMais
Copy link

@kranthi610 Still doesnt work...

@kranthi610
Copy link

@kranthi610 Still doesnt work...

share me the swagger UI for API

@K2ouMais
Copy link

K2ouMais commented May 18, 2020

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
Copy link

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

*@OA\Response(

  • response=200,
    
  • description="successful operation",
    
  • @OA\MediaType(
    
  •      mediaType="application/json",
    
  •      @OA\Schema(
    
  •           type="array",
    
  •            @OA\Items(
    
  •                ref="#/components/schemas/Adress"
    
  •            )
    
  •      )
    
  • ),
    

@OA\MediaType(

  •      mediaType="application/xml",
    
  •      @OA\Schema(
    
  •           type="array",
    
  •            @OA\Items(
    
  •                ref="#/components/schemas/Address"
    
  •            )
    
  •      )
    
  • )
    

*),
*
*@OA\Response(

  • response=400,
    
  •  description="Invalid value"
    

*),
*@OA\Response(

  • response=401,
    
  •  description="Unauthenticated"
    

*),
*security={

  •       {"bearerAuth": {}}
    
  •     }
    

*)
*/

this is how you do in base controller

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

  • @OA\Info(
  • description="Access to ",
    
  • version="1.0.0",
    
  • title="Live API",
    
  • ),
  • @OA\Tag(
  • name="Adress",
    
  • description="Everything about Adresses",
    
  • ),
  • @OA\Server(
  • description="SwaggerHUB API Mocking",
    
  • url="http://dev.api.test.org"
    
  • )
  • @OA\SecurityScheme(
  • securityScheme="bearerAuth",
    
  • type="http",
    
  • scheme="bearer",
    
  • bearerFormat="JWT",
    
  • )
    */

@K2ouMais
Copy link

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
Copy link

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
Copy link

buildsomethingdifferent commented Dec 3, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests