L5-Swagger icon indicating copy to clipboard operation
L5-Swagger copied to clipboard

How to pass cookies to api

Open max10rogerio opened this issue 4 years ago • 2 comments

  • L5-Swagger Version: 8.4.1 (composer show | grep l5-swagger)
  • PHP Version (php -v): 8.1.8
  • OS: Ubuntu 20.04

Description:

How to pass cookies to api?

Swagger UI Config

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{config('l5-swagger.documentations.'.$documentation.'.api.title')}}</title>
    <link rel="stylesheet" type="text/css" href="{{ l5_swagger_asset($documentation, 'swagger-ui.css') }}">
    <link rel="icon" type="image/png" href="{{ l5_swagger_asset($documentation, 'favicon-32x32.png') }}" sizes="32x32"/>
    <link rel="icon" type="image/png" href="{{ l5_swagger_asset($documentation, 'favicon-16x16.png') }}" sizes="16x16"/>
    <!-- Load the HierarchicalTags Plugin -->
    <script src="https://unpkg.com/swagger-ui-plugin-hierarchical-tags"></script>
    <style>
    html
    {
        box-sizing: border-box;
        overflow: -moz-scrollbars-vertical;
        overflow-y: scroll;
    }
    *,
    *:before,
    *:after
    {
        box-sizing: inherit;
    }

    body {
      margin:0;
      background: #fafafa;
    }
    </style>
</head>

<body>
<div id="swagger-ui"></div>

<script src="{{ l5_swagger_asset($documentation, 'swagger-ui-bundle.js') }}"></script>
<script src="{{ l5_swagger_asset($documentation, 'swagger-ui-standalone-preset.js') }}"></script>
<script>
    window.onload = function() {
        // Build a system
        const ui = SwaggerUIBundle({
            dom_id: '#swagger-ui',
            url: "{!! $urlToDocs !!}",
            withCredentials: true, // enable cookies here
            operationsSorter: {!! isset($operationsSorter) ? '"' . $operationsSorter . '"' : 'null' !!},
            configUrl: {!! isset($configUrl) ? '"' . $configUrl . '"' : 'null' !!},
            validatorUrl: {!! isset($validatorUrl) ? '"' . $validatorUrl . '"' : 'null' !!},
            oauth2RedirectUrl: "{{ route('l5-swagger.'.$documentation.'.oauth2_callback', [], $useAbsolutePath) }}",

            requestInterceptor: function(request) {
                request.headers['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
                return request;
            },

            presets: [
                SwaggerUIBundle.presets.apis,
                SwaggerUIStandalonePreset
            ],

            plugins: [
                SwaggerUIBundle.plugins.DownloadUrl,
                HierarchicalTagsPlugin
            ],

            layout: "StandaloneLayout",
            docExpansion : "{!! config('l5-swagger.defaults.ui.display.doc_expansion', 'none') !!}",
            filter: {!! config('l5-swagger.defaults.ui.display.filter') ? 'true' : 'false' !!},
            persistAuthorization: "{!! config('l5-swagger.defaults.ui.authorization.persist_authorization') ? 'true' : 'false' !!}",

        })

        window.ui = ui
    }
</script>
</body>
</html>

Config image

Curl

curl -X 'GET' \
  'http://localhost:8080/v1/configs/branches?field=name&direction=ASC&page=1&items_per_page=20&type=json' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJraWQiOiJiOThhMDllZTIyYjE0M2I1OGRlMWE3MGFlNjZkMDAwMCIsImFsZyI6IlJTMjU2In0.eyJqdGkiOiJhM2Q0MzZjMS1kMDQ4LTQyYjUtYTUzNy1lYmQzYzkzNzIxZWMiLCJpc3MiOiJuenJ4UzF3Y3IzbGhqa0JKYVliT2Y0RjNCTEd2Y0dFVyIsImlhdCI6MTY2Mzg1MjA3MSwic3ViIjoiNzg3N2U1YjMtYzRlMy00ZDc5LTgzMjAtOTQxN2I0OWJlZTIwIiwiZXhwIjoxNjYzODU1NjcxLCJ0c2kiOiJlNmQyOTdiMS0yOGEyLTQ2YWYtODQwOC1jN2YyNGZkMDFjNzktYWNjZXNzIiwidG9rZW5fdXNlIjoiYWNjZXNzIiwiZW1haWwiOiJtYXguY2FtYXJnb0BnYXppbi5jb20uYnIiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsInJ0ZCI6ImdCYS1hTkpuTFllUy1FUnBkRzliZmZxNHUtT0IyTTJ6OWwzSVdFSzV2ajh6SjBsNm9oMlM0SktyeENCY0ZyUEgiLCJub25jZSI6bnVsbCwic2NvcGVzIjoib3BlbmlkIGVtYWlsIn0.DtNXzl9uQgUObJjV-88I0YR335H_56AnyRKd88ts5pshk_aRKeEh0Cl0zvsqiTkkrwBHiyVLip-NGKuyVcEZb7XIalIn42a8-xVaFJu8YCMil9xY7yS0kreTxh98xelZPlK02Yh_KusVL8Cz47FYJTWIr3zU3KeA3uyaXG1m7OJW4QxfhreHxld96PEUwQn5olMSM-E3iLADyyUdza7YOpj0ACD4VPA4OwQ-YpHqoz0BloaUCzgq1HucTx4lhGK5FbOE_cKBOCISb2ldZI1cZN9xj8nSC-lG8m5MJQLbPZwROk2jUE0-TqgmcoZgG3uevtC1pZdGKaVQMUSLlKU0HA' \
  -H 'Cookie: company_id=5491a88f-ddb2-4948-90b8-b1596b848ad1' \
  -H 'X-CSRF-TOKEN: '

image

image

max10rogerio avatar Sep 22 '22 15:09 max10rogerio

Issue Summary

I am facing a similar issue using Laravel 12 with PHP 8.3. My application is a fully API-based backend—there are no Blade views involved, and all routes are defined under routes/api.php. The Swagger/OpenAPI annotations are correctly set up, and I have meticulously followed all steps from the official documentation.

Main Problem

Despite this, whenever I try to make requests via the Swagger UI in the browser, the requests do not execute as expected. Instead, I consistently receive a 419 CSRF Token Mismatch error.
This is confusing because my application does not utilize Laravel sessions at all—authentication is handled exclusively through Sanctum tokens.

What I Have Tried

  • Swagger Annotations: All annotations are valid; the documentation is generated and displayed correctly.
  • Route Placement: All API endpoints are in routes/api.php, not in routes/web.php.
  • CSRF Middleware: I verified that the routes are not using the web middleware group, which is responsible for CSRF protection.
  • Session Middleware: The session middleware is not used in my API, as there is no session-based authentication.
  • Swagger UI Configuration: I tried both including and commenting out the requestInterceptor in the Swagger UI that would add the CSRF token to requests.
    • When the interceptor was active, it attempted to send a CSRF token (which doesn't exist in my case), still resulting in a 419 error.
    • When I commented it out, the requests stopped being sent altogether, or errors persisted.
  • Sanctum Configuration: My API uses Sanctum for token-based authentication (not SPA authentication). The guards are set up properly, and controllers use auth:sanctum middleware.
  • CORS: CORS settings are open for API routes and not blocking requests.
  • No config/csrf.php: In Laravel 12, there is no default config/csrf.php, and creating one manually does not resolve the issue, as the framework does not reference it by default.

Key Observations

  • CSRF tokens should not be required for stateless API routes (those in routes/api.php), especially when using token-based authentication like Sanctum.
  • The 419 CSRF error suggests that, for some reason, the CSRF middleware is still being applied or expected for API routes, possibly due to an unexpected middleware or guard configuration.
  • Swagger UI is not compatible with Laravel's session/cookie-based CSRF protection unless specifically configured to handle it—which is not the case for stateless APIs.

What I Need

Is there any definitive way to completely bypass or ignore CSRF token validation for all API routes in Laravel 12, especially when using Sanctum tokens and no sessions?
I want to ensure my API remains stateless, and that Swagger UI can be used for testing without running into CSRF issues.

Any guidance or up-to-date best practices for Laravel 12 in this scenario would be greatly appreciated!

Issue Summary

I am facing a similar issue using Laravel 12 with PHP 8.3. My application is a fully API-based backend—there are no Blade views involved, and all routes are defined under routes/api.php. The Swagger/OpenAPI annotations are correctly set up, and I have meticulously followed all steps from the official documentation.

Main Problem

Despite this, whenever I try to make requests via the Swagger UI in the browser, the requests do not execute as expected. Instead, I consistently receive a 419 CSRF Token Mismatch error. This is confusing because my application does not utilize Laravel sessions at all—authentication is handled exclusively through Sanctum tokens.

What I Have Tried

  • Swagger Annotations: All annotations are valid; the documentation is generated and displayed correctly.

  • Route Placement: All API endpoints are in routes/api.php, not in routes/web.php.

  • CSRF Middleware: I verified that the routes are not using the web middleware group, which is responsible for CSRF protection.

  • Session Middleware: The session middleware is not used in my API, as there is no session-based authentication.

  • Swagger UI Configuration: I tried both including and commenting out the requestInterceptor in the Swagger UI that would add the CSRF token to requests.

    • When the interceptor was active, it attempted to send a CSRF token (which doesn't exist in my case), still resulting in a 419 error.
    • When I commented it out, the requests stopped being sent altogether, or errors persisted.
  • Sanctum Configuration: My API uses Sanctum for token-based authentication (not SPA authentication). The guards are set up properly, and controllers use auth:sanctum middleware.

  • CORS: CORS settings are open for API routes and not blocking requests.

  • No config/csrf.php: In Laravel 12, there is no default config/csrf.php, and creating one manually does not resolve the issue, as the framework does not reference it by default.

Key Observations

  • CSRF tokens should not be required for stateless API routes (those in routes/api.php), especially when using token-based authentication like Sanctum.
  • The 419 CSRF error suggests that, for some reason, the CSRF middleware is still being applied or expected for API routes, possibly due to an unexpected middleware or guard configuration.
  • Swagger UI is not compatible with Laravel's session/cookie-based CSRF protection unless specifically configured to handle it—which is not the case for stateless APIs.

What I Need

Is there any definitive way to completely bypass or ignore CSRF token validation for all API routes in Laravel 12, especially when using Sanctum tokens and no sessions? I want to ensure my API remains stateless, and that Swagger UI can be used for testing without running into CSRF issues.

Any guidance or up-to-date best practices for Laravel 12 in this scenario would be greatly appreciated!

update !

this code solved my issue at app/bootstrap/app.php ->withMiddleware(function (Middleware $middleware) { $middleware->statefulApi(); $middleware->validateCsrfTokens(except: [ 'api/*' ]); })