Home > Backend Development > PHP Tutorial > Documenting API authentication in Laravel with Scramble

Documenting API authentication in Laravel with Scramble

Emily Anne Brown
Release: 2025-03-05 15:45:15
Original
576 people have browsed it

This tutorial demonstrates common Laravel API authentication methods and their documentation using Scramble, a modern API documentation tool. Scramble fully supports OpenAPI 3.1.0 security specifications, enabling comprehensive authentication method documentation.

Sanctum Authentication

Sanctum, a popular Laravel authentication method, supports both stateless and stateful authentication. For stateless authentication, a bearer token is sent in the Authorization header: Authorization: Bearer ***. Scramble documents this using a service provider's boot method:

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')
            );
        });
}
Copy after login
Copy after login

Documenting API authentication in Laravel with Scramble

This sets a default bearer token security scheme for all endpoints. Stateful authentication, if Scramble's documentation routes are correctly configured, will function automatically within the "Try it out" feature.

Passport Authentication

For OAuth2 authentication, OpenAPI utilizes the oauth2 security scheme. Scramble allows precise configuration:

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');
                    })
            );
        });
}
Copy after login

Scopes can be defined globally or with granular control. While Stoplight Elements (Scramble's default UI) displays oauth2 requirements, other UIs (Scalar, Swagger) facilitate direct token acquisition from the documentation.

Documenting API authentication in Laravel with Scramble

Documenting Sanctum's oauth/token Endpoint

Documenting Sanctum's oauth/token endpoint is achievable with a community-contributed Scramble extension: https://www.php.cn/link/e14c38bd11cd714b970735ade2f233fa. Remember to include it in Scramble's documentable routes:

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

Documenting API authentication in Laravel with Scramble

Custom Authentication

Multiple Header Authentication

For authentication requiring multiple headers, specify them within 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' => [],
            ]);
        });
}
Copy after login

This mandates both X-Tenant and Authorization headers.

API Token in Query Parameters

If the API token is a query parameter, use:

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')
            );
        });
}
Copy after login

Refer to Scramble's documentation for more security scheme details: https://www.php.cn/link/2a174f994bb16b9b11e6ea5c00a671c5.

Excluding Routes from Authentication

The @unauthenticated PHPDoc annotation excludes routes from authentication. Operation transformers provide more flexibility. For instance, to exempt routes lacking auth: middleware:

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')
            );
        });
}
Copy after login
Copy after login

This automatically designates routes without authentication middleware as public. This approach also allows assigning specific security requirements to operations.

Conclusion

OpenAPI and Scramble offer robust solutions for documenting various API authentication methods, including automated handling based on middleware, minimizing manual annotations. Explore Scramble at https://www.php.cn/link/0fcbc3c0cf262c771001930af2406bbc.

The above is the detailed content of Documenting API authentication in Laravel with Scramble. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template