springdoc / springdoc-openapi

Library for OpenAPI 3 with spring-boot
https://springdoc.org
Apache License 2.0
3.24k stars 489 forks source link

Enabling CSRF support upsets Swagger-UI #1817

Closed sjerman closed 2 years ago

sjerman commented 2 years ago

Config: Spring Boot : 2.7.2 springdoc: 1.6.11 Swagger-UI: 4.14.0

Describe the bug When I enable csrf support, the swagger-ui starts showing 'Failed to load remote configuration.'

The generated swagger-initializer.js is:

window.onload = function() {
  //<editor-fold desc="Changeable Configuration Block">

  // the following lines will be replaced by docker/configurator, when it runs in a docker-container
  window.ui = SwaggerUIBundle({
    url: "https://petstore.swagger.io/v2/swagger.json",
    dom_id: '#swagger-ui',
    deepLinking: true,
    requestInterceptor: (request) => {
            const value = window.sessionStorage.getItem('XSRF-TOKEN');
            const currentURL = new URL(document.URL);
            const requestURL = new URL(request.url, document.location.origin);
            const isSameOrigin = (currentURL.protocol === requestURL.protocol && currentURL.host === requestURL.host);
            if (isSameOrigin) request.headers['X-CSRF-TOKEN'] = value.replace(/['"]+/g,'');
            return request;
        },
        presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout" ,

  "configUrl" : "/v3/api-docs/swagger-config",
  "docExpansion" : "none",
  "filter" : "true",
  "validatorUrl" : ""

  });

  //</editor-fold>
};

If I remove the CSRF stuff from application.yml it works...

To Reproduce Set the following in application.yaml file:

springdoc:
  swagger-ui:
    docExpansion: none
    filter: true
    csrf:
      enabled: true
      cookie-name: CSRF-TOKEN
      header-name: X-CSRF-TOKEN
      use-session-storage: true

Expected behavior Swagger-UI should work

Screenshots

Screenshot 2022-08-26 at 10 56 22 AM
sjerman commented 2 years ago

Sorted it - user error. I should have left use-session-storage = false.