Security
Security is declared in two steps: the schemes in Components::securitySchemes(), then the requirements, for the
whole document with OpenApi::security() or per operation with Operation::security().
Declaring the schemes
One shortcut per type; the argument is the scheme name.
use Ark4ne\OpenApiWriter\Objects\Components;
use Ark4ne\OpenApiWriter\Objects\OAuthFlow;
use Ark4ne\OpenApiWriter\Objects\OAuthFlows;
use Ark4ne\OpenApiWriter\Objects\SecurityScheme;
$components = Components::create()->securitySchemes(
SecurityScheme::http('bearer')
->scheme('bearer')
->bearerFormat('JWT'),
SecurityScheme::apiKey('apiKey')
->name('X-API-Key')
->in('header'),
SecurityScheme::oauth2('oauth')->flows(
OAuthFlows::create()->authorizationCode(
OAuthFlow::create()
->authorizationUrl('https://auth.example.com/authorize')
->tokenUrl('https://auth.example.com/token')
->scopes([
'books:read' => 'Read books',
'books:write' => 'Write books',
]),
),
),
SecurityScheme::openIdConnect('oidc')
->openIdConnectUrl(
'https://auth.example.com/.well-known/openid-configuration',
),
);
SecurityScheme::mutualTLS() exists from OpenAPI 3.1. OAuthFlows has implicit(), password(),
clientCredentials(), authorizationCode(), and deviceAuthorization() from 3.2.
Requiring them
A SecurityRequirement maps scheme names to the scopes it needs ([] when none). The schemes of one requirement all
apply together; several requirements are alternatives.
use Ark4ne\OpenApiWriter\Objects\SecurityRequirement;
// A bearer token OR an API key, on every operation.
$document = $document
->components($components)
->security(
SecurityRequirement::create()->schemes(['bearer' => []]),
SecurityRequirement::create()->schemes(['apiKey' => []]),
);
Overriding per operation
An operation's security() replaces the document's:
use Ark4ne\OpenApiWriter\Objects\Operation;
use Ark4ne\OpenApiWriter\Objects\Response;
// OAuth2 with a scope.
$purge = Operation::delete()
->operationId('admin.books.purge')
->security(
SecurityRequirement::create()->schemes(['oauth' => ['books:write']]),
)
->responses(Response::noContent());
Two special cases:
// Public: no authentication.
Operation::post()
->security()
->responses(Response::ok());
{
"responses": {
"200": { "description": "OK" }
},
"security": []
}
// Optional: a bearer token, or nothing.
Operation::get()->security(
SecurityRequirement::create()->schemes(['bearer' => []]),
SecurityRequirement::create(),
);
{
"security": [
{ "bearer": [] },
{}
]
}
The validator checks that every requirement names a declared scheme, with OAuth2 scopes that exist
(SecurityRequirementsRule). Scopes on a non-OAuth2 scheme exist from OpenAPI 3.1.