amazon-web-servicesswaggerswagger-ui

How to calculate AWS signature V4 in Swagger before request


For our AWS API Endpoints we use AWS_IAM authorization and want to make a call from Swagger UI. To make a successful call there must be 2 headers 'Authorization' and 'x-amz-date'. To form 'Authorization' we use following steps from aws doc. We must to change 'x-amz-date' with every call to go through authorization. The question is: How to write script in Swagger to sign request, which run every time before request send to aws? (We know how to specify both headers one time before loading Swagger page, but this process should be re-run before every call).

Thanks in advance.


Solution

  • There is built-in support in swagger-js to add requestInterceptors to do just this. The swagger-ui project uses swagger-js under the hood.

    Simply create a request interceptor like such:

    requestInterceptor: {
      apply: function (request) {
        // modify the request object here
        return request;
      }
    }
    

    and apply it to your swagger instance on creation:

    window.swaggerUi = new SwaggerUi({
      url: url,
      dom_id: "swagger-ui-container",
      requestInterceptor: requestInterceptor,
    

    Here you can set headers in the request object (note, this is not the standard javascript http request object, inspect it for details). But you do have access to all headers here, so you can calculate and inject them as needed.