cebe / php-openapi

Read and write OpenAPI yaml/json files and make the content accessible in PHP objects.
MIT License
466 stars 88 forks source link

How to use Security and SecurityRequirement #75

Open nadar opened 4 years ago

nadar commented 4 years ago

I am not sure how to use Security in combination with SecurityRequirements.

The Security Schema defined:

new OpenApi([
    'components' => new Components([
            'securitySchemes' => [
                'BearerAuth' => new SecurityScheme([
                    'type' => 'http',
                    'scheme' => 'bearer',
                    'bearerFormat' => 'AuthToken and JWT Format' # optional, arbitrary value for documentation purposes
                ])
            ],
   ]),
]);

Now the security schema is created (components).

How do i assign this security schema for an specific operation?

return new PathItem([
    'get' => new Operation([
        'security' => [new SecurityRequirement(['BearerAuth'])],
    ])
]);

Thanks for the great library and maybe it clarifies this task also for others.

cebe commented 4 years ago

I have never used Security and SecurityRequirement definitions before, but according to this documentation (https://swagger.io/docs/specification/authentication/) it seems it needs to look like this in YAML:

    get:
      security:
        - BearerAuth: []
#...
      summary: Gets the account billing info
      responses:
        '200':
          description: OK

So the correct way to create such a spec from PHP code would be:

return new PathItem([
    'get' => new Operation([
        'security' => [new SecurityRequirement(['BearerAuth' => []])],
        // ...
    ])
]);

I have not tried it, but this should work as far as I see. I also see there is room for improvement on the class API here, so even if this answers your question, please keep the issue open.