7

Is there a way to automatically include a CSRF header to requests made from swagger ui, when using the one bundled with springdoc-openapi?

A similar solution appears to be implemented in springfox (GitHub), but I find no information about whether this is possible to accomplish with springdoc-openapi.

starman
  • 356
  • 1
  • 4
  • 11

2 Answers2

8

CSRF token are by default supported, if you are using standard headers.(for example using spring-security headers)

If the CSRF Token is required, swagger-ui automatically sends the new XSRF-TOKEN during each HTTP REQUEST.

That said - if your XSRF-TOKEN isn't standards-based, you can use a requestInterceptor to manually capture and attach the latest xsrf token to requests programmatically via spring resource transformer:

Also, CSRF is becoming less relevant over time, as browsers add user-agent level support for controls over cross-origin request cookie inclusion.

Starting from release v1.4.4 of springdoc-openapi, a new property is added to enable CSRF support, while using standard header names:

springdoc.swagger-ui.csrf.enabled=true
  • Thank you, I will try using the requestInterceptor. I can't however get the automatic support with standard headers, here is my minimal example: https://github.com/Stjerndal/springdoc-csrf. Am I missing something there to get it working? – starman Jun 11 '20 at 08:18
  • 1
    starman, you can test with the latest snapshot of springdoc-openapi, which adds the support of CSRF out of the box: https://github.com/springdoc/springdoc-openapi/issues/776 –  Jul 11 '20 at 09:45
  • Even if my server is configured properly to check csrf token, when I try to send a request from swagger-ui, it never sends the expected default header – Fabio O. Padilha Apr 24 '23 at 21:19
0

SwaggerUI not including CSRF-TOKEN into request by default

If you are using React you can reuse the following code to include it manually:

import React from 'react';
import SwaggerUI from "swagger-ui-react"
import "swagger-ui-react/swagger-ui.css"
import Cookies from 'universal-cookie';

const cookies = new Cookies();

const DocsPage = () => (
  <SwaggerUI url="/v2/api-docs" requestInterceptor={(request) => {
    request.headers['X-XSRF-TOKEN'] = cookies.get("XSRF-TOKEN")
  }}/>
);

export default DocsPage;
Peter Gyschuk
  • 919
  • 8
  • 12