.Net Core Swashbuckle在重定向上跳过授权标头

时间:2019-06-13 07:37:34

标签: c# .net-core swagger-ui swashbuckle minio

在.Net Core Web API中,我使用Swashbuckle集成了Swagger。该API受保护,因此在Swagger UI中进行某些请求之前,需要先授权和登录。这一切都很好。

现在,一个API调用将创建一个预签名URL,并将HTTP重定向返回到文件服务器(该预签名URL)。

问题是Swagger UI将带有JWT令牌的授权标头发送到文件服务器(MinIO)。这将导致文件服务器接收两种不同的身份验证机制,并以无效请求进行响应。

是否有一种方法可以影响Swagger UI如何处理重定向或不发送重定向令牌?

1 个答案:

答案 0 :(得分:1)

我也遇到了这个问题,意识到fetch重定向到预先签名的S3 URL时,您不能阻止它从您的API发送授权标头。

最终,我可以通过将Swagger的responseInterceptor配置参数与自定义函数一起使用来实现此功能,该自定义函数检测到来自S3的错误请求(400)响应,然后重新发出fetch请求与credentials: 'omit'

这是我对Swagger的自定义响应拦截器:

// swagger-ui-extensions.js

function serializeHeaderValue(value) {
  const isMulti = value.includes(', ');
  return isMulti ? value.split(', ') : value;
}

function serializeHeaders(headers = {}) {
  return Array.from(headers.entries()).reduce((acc, [header, value]) => {
    acc[header] = serializeHeaderValue(value);
    return acc;
  }, {});
}

function myResponseInterceptor(response) {
  // NOTE: Additional checks should probably be added whether to re-issue the fetch. This was just an initial starting point.
  if (response.ok === false && response.status === 400 && response.headers['server'] === 'AmazonS3') {
    // Here is the important part, re-issue fetch but don't allow our Authentication header to flow
    response = fetch(response.url, { credentials: 'omit' })
      .then(nativeResponse => {
        // We can't return the native response because Swagger UI attempts to assign the header property (and potentially other properties
        // too) on the response. So return a serialized clone of the native response. FYI, this is the same exact logic from Swagger's fake
        // implementation of fetch.
        const getBody = nativeResponse.blob || nativeResponse.buffer;
        return getBody.call(nativeResponse).then(body => {
          return {
            ok: nativeResponse.ok,
            url: nativeResponse.url,
            status: nativeResponse.status,
            statusText: nativeResponse.statusText,
            headers: serializeHeaders(nativeResponse.headers),
            data: body
          };
        });
      });
  }
  return response;
}

然后,在myResponseInterceptor中初始化Swagger UI时,我必须指定自定义index.html

      // (other code omitted for brevity...)

      // Make sure to include your custom JS in the page
      // <script src="./swagger-ui-extensions.js"></script>

      // Specifying the custom responseInterceptor here...
      configObject.responseInterceptor = myResponseInterceptor;

      // Begin Swagger UI call region

      const ui = SwaggerUIBundle(configObject);

      ui.initOAuth(oauthConfigObject);

      // End Swagger UI call region

      window.ui = ui;

我正在使用ASP.NET Core,并按照以下说明为Swagger UI提供了自己的index.htmlhttps://github.com/domaindrivendev/Swashbuckle.AspNetCore#customize-indexhtml

毕竟,这出乎意料地起作用,我能够在Swagger中看到来自S3的重定向响应。