Try Depot: Bring ultra-fast, remote Docker builds directly to your Laravel workflow

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
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech
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
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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 →
Debugbar releases v4.2.0 and add a new Boost skill image

Debugbar releases v4.2.0 and add a new Boost skill

Read article
New Expressive Model Attributes in Laravel 13.2.0 image

New Expressive Model Attributes in Laravel 13.2.0

Read article
Inertia.js v3.0.0 Is Here with Optimistic Updates, useHttp, and More image

Inertia.js v3.0.0 Is Here with Optimistic Updates, useHttp, and More

Read article
Laravel Boost v2.4.0 Adds Security Audits and a Laravel Best Practices Skill image

Laravel Boost v2.4.0 Adds Security Audits and a Laravel Best Practices Skill

Read article
Building Transaction-Safe Multi-Document Operations in Laravel image

Building Transaction-Safe Multi-Document Operations in Laravel

Read article
Ship AI with Laravel: Building Your First Agent with Laravel 13's AI SDK image

Ship AI with Laravel: Building Your First Agent with Laravel 13's AI SDK

Read article