Outsource Laravel Development Partner - $3200/Month | Bacancy

Documenting API authentication in Laravel with Scramble

Last updated on by

Documenting API authentication in Laravel with Scramble image

In this post, we'll review common API authentication methods in Laravel and how to document them using Scramble – the modern API documentation tool for Laravel.

The OpenAPI specification supports multiple API authentication methods. With a recent update, Scramble now fully supports OpenAPI 3.1.0 security specification, allowing you to document any authentication method available in the specification.

Sanctum authentication

Sanctum is my go-to authentication method, and I bet it's yours too!

For stateless authentication, Sanctum allows you to send an authentication token in the Authorization header:

Authorization: Bearer ***

With Scramble, you can document this authentication using the following code. It should be added to the boot method of any service provider:

use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;
 
public function boot()
{
Scramble::configure()
->withDocumentTransformers(function (OpenApi $openApi) {
$openApi->secure(
SecurityScheme::http('bearer')
);
});
}

This sets a default security scheme for all endpoints.

If you use Sanctum's stateful authentication and Scramble’s documentation routes are on the correct domain, your authentication session will work automatically in "Try it out."

Passport authentication

For OAuth2 authentication, OpenAPI provides the oauth2 security scheme.

Scramble allows you to specify exactly how oauth2 works:

;
 
use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;
use Dedoc\Scramble\Support\Generator\SecuritySchemes\OAuthFlow;
 
public function boot()
{
Scramble::configure()
->withDocumentTransformers(function (OpenApi $openApi) {
$openApi->secure(
SecurityScheme::oauth2()
->flow('authorizationCode', function (OAuthFlow $flow) {
$flow
->authorizationUrl(config('app.url').'/oauth/authorize')
->tokenUrl(config('app.url').'/oauth/token')
->addScope('*', 'all');
})
);
});
}

You can define all scopes as shown here or specify granular scopes for your application.

While the Stoplight Elements UI (Scramble's default UI) displays the oauth2 requirement, other UIs (Scalar, Swagger) also allow users to obtain API tokens directly from the documentation.

Documenting Sanctum's oauth/token endpoint

You can document Sanctum’s oauth/token endpoint using Scramble. Here’s a community-created extension that helps with this: https://gist.github.com/tech-codivores/ddce2b10a64f06fe0b1bcd4868c17039

Before using the extension, make sure to include it in Scramble’s documentable routes:

Scramble::configure()
->routes(function (Route $r) {
return Str::startsWith($r->uri, 'api/'])
|| $r->uri === 'oauth/token';
})

Custom authentication

Multiple header authentication

If your authentication requires multiple headers, you can specify them in the API security requirement:

use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;
 
public function boot()
{
Scramble::configure()
->withDocumentTransformers(function (OpenApi $openApi) {
$openApi->components->securitySchemes['tenant'] = SecurityScheme::apiKey('header', 'X-Tenant');
$openApi->components->securitySchemes['bearer'] = SecurityScheme::http('bearer');
 
$openApi->security[] = new SecurityRequirement([
'tenant' => [],
'bearer' => [],
]);
});
}

In this case, authentication requires both X-Tenant and Authorization headers.

API token in query parameters

If your API token is passed as a query parameter, you can document it with this snippet:

use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme;
 
public function boot()
{
Scramble::configure()
->withDocumentTransformers(function (OpenApi $openApi) {
$openApi->secure(
SecurityScheme::apiKey('query', 'api_token');
);
});
}

You can learn more about available security schemes in Scramble’s documentation: https://scramble.dedoc.co/usage/authentication.

Excluding routes from authentication requirements

To exclude a specific route from authentication, use the @unauthenticated PHPDoc annotation:

/**
* @unauthenticated
*/
public function index(Request $request)
{
return response()->json(/* some data */);
}

However, operation transformers offer more flexibility.

For example, to remove authentication requirements from routes without auth: middleware:

public function boot()
{
Scramble::configure()
->withOperationTransformers(function (Operation $operation, RouteInfo $routeInfo) {
$routeMiddleware = $routeInfo->route->gatherMiddleware();
 
$hasAuthMiddleware = collect($routeMiddleware)->contains(
fn ($m) => Str::startsWith($m, 'auth:')
);
 
if (! $hasAuthMiddleware) {
$operation->security = [];
}
})
}

This automatically marks routes without authentication middleware as public. Using this approach, you can also assign specific security requirements to an operation.

Conclusion

There are many ways to implement API authentication, and OpenAPI covers most of them.

With Scramble, you can document your API’s authentication setup and even automate authentication requirements based on middleware, avoiding manual annotations.

If you haven’t tried Scramble yet, give it a shot! https://scramble.dedoc.co

Roman Lytvynenko photo

Working on https://scramble.dedoc.co – Modern Laravel OpenAPI (Swagger) documentation generator.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Laravel Boost Update Adds Support for the New MCP Protocol image

Laravel Boost Update Adds Support for the New MCP Protocol

Read article
Pest Adds withHost for Browser Testing Subdomains in Laravel image

Pest Adds withHost for Browser Testing Subdomains in Laravel

Read article
Run Artisan Make Commands in Laravel VS Code Extension image

Run Artisan Make Commands in Laravel VS Code Extension

Read article
Livewire 4 Is Dropping Next Week, and wire:transition Makes Animations Effortless image

Livewire 4 Is Dropping Next Week, and wire:transition Makes Animations Effortless

Read article
Laravel 12.45.1, 12.45.2, and 12.46.0 Released image

Laravel 12.45.1, 12.45.2, and 12.46.0 Released

Read article
"Don't Remember" Form Helper Added in Inertia.js 2.3.7 image

"Don't Remember" Form Helper Added in Inertia.js 2.3.7

Read article