Tinkerwell - The PHP Scratchpad

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
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
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
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
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
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
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 →
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article