SolvedL5 Swagger oauth2 + passport = Bearer <token>

"Authorization" : "Bearer token213315454Sample"

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

50 Answers

✔️Accepted Answer

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

Other Answers:

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": {}}
    
  •     }
    

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...

Why not anyone create a tutorial this?

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.

More Issues: