Scramble 0.11.0 is here! Laravel Data support, schema enforcement and more
Learn more

Security

On this page
Scramble PRO
Comprehensive API documentation generation for Spatie’s Laravel Data and Laravel Query Builder.
Are you a visual learner?
Get most out of Scramble with in-depth screencasts.

Most likely, your API is protected by some sort of authentication. OpenAPI has plenty of ways to describe the API (see full documentation of spec here https://spec.openapis.org/oas/v3.1.0#security-scheme-object).

Adding security scheme

Scramble allows you to document how your API is secured. To document this, you can use Scramble::afterOpenApiGenerated method and add security information to OpenAPI document using secure method.

You should call afterOpenApiGenerated in the boot method of some of your service providers. This method accepts a callback that accepts an OpenAPI document as a first argument.

The secure method on OpenApi object accepts security scheme as an argument. It makes the security scheme default for all endpoints.

use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Scramble::afterOpenApiGenerated(function (OpenApi $openApi) {
$openApi->secure(
SecurityScheme::apiKey('query', 'api_token')
);
});
}

Security scheme examples

Here are some common examples of security schemes objects you may have in your API. For full list of available methods check implementation of SecurityScheme class.

Bearer

One of the most common ways to add auth protection to the API is to use Authorization header with Bearer $token value. If you use this way of auth, you can document it using:

SecurityScheme::http('bearer');

API Key

When the API token is passed as a query parameter in URL (https://someapi.com/api/items?api_token=0000_00_0001), the next security schema can be used:

SecurityScheme::apiKey('query', 'api_token');

Bearer JWT

SecurityScheme::http('bearer', 'JWT');

Basic HTTP

SecurityScheme::http('basic');

Oauth2

SecurityScheme::oauth2()
->flow('implicit', function (OAuthFlow $flow) {
$flow
->authorizationUrl('https://example.com/api/oauth/dialog')
->addScope('write:pets', 'modify pets in your account');
});

Excluding a route from security requirements

You can exclude a route from security requirements by adding @unauthenticated annotation to the route method’s PHPDoc comment block.

/**
* @unauthenticated
*/
public function index(Request $request)
{
return response()->json(/* some data */);
}
Scramble PRO
Comprehensive API documentation generation for Spatie’s Laravel Data and Laravel Query Builder.