Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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.

Curotec logo

Curotec

Hire the top Latin American Laravel talent. Flexible engagements, budget optimized, and quality engineering.

Curotec
Bacancy logo

Bacancy

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

Bacancy
Laravel Forge logo

Laravel Forge

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

Laravel Forge
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
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Connecting Laravel Socialite with Google Client PHP Library image

Connecting Laravel Socialite with Google Client PHP Library

Read article
Create Self-Contained PHP Executables with PHPacker image

Create Self-Contained PHP Executables with PHPacker

Read article
String Manipulation with Laravel's remove Method image

String Manipulation with Laravel's remove Method

Read article
Stargazing in Your Laravel App with Intervention Zodiac image

Stargazing in Your Laravel App with Intervention Zodiac

Read article
Simple Cookie Consent Packge for Laravel image

Simple Cookie Consent Packge for Laravel

Read article
Leveraging Laravel's Conditional Ping Methods for Task Monitoring image

Leveraging Laravel's Conditional Ping Methods for Task Monitoring

Read article