jamesmbourne / aws4-axios

Axios request interceptor for signing requests with AWSv4
MIT License
108 stars 39 forks source link

Need to clear headers before retrying #11

Open thejuan opened 3 years ago

thejuan commented 3 years ago

In case this helps anyone else using this in conjunction with axios-retry requires resetting the headers before re-signing. I've added this after I add the aws4 interceptor.

 this.$axios.interceptors.request.use((config) => {
      // Need to remove old signing headers if this is a retry
      if ((config["axios-retry"] as any)?.retryCount > 0) {
        logger.info(`Cleaning headers from previous request`);
        for (const key of Object.keys(config.headers).filter((k) => k.startsWith("X-Amz"))) {
          delete config.headers[key];
        }
        delete config.headers["Authorization"];
      }
      return config;
    });
philiptolk commented 3 years ago

I am having a similiar issue trying to change the account after setting it once.


const axios = require('axios');
const aws4Interceptor = require ("aws4-axios").aws4Interceptor;

function set_interceptor(sessionToken, accessKeyId, secretAccessKey){
  axios.interceptors.request.handlers.length = 0;
  const interceptor = aws4Interceptor({
        region: region,
        service: service
      }, {
        accessKeyId: accessKeyId,
        secretAccessKey: secretAccessKey,
        sessionToken: sessionToken
      });

    axios.interceptors.request.use(interceptor);
}
eyalroth commented 1 year ago

@thejuan Thank you for this discovery and workaround!

Here's my solution in TypeScript:

import axios, { AxiosRequestConfig } from 'axios';
import { aws4Interceptor } from 'aws4-axios';

type Config = AxiosRequestConfig & { _originalHeaders?: AxiosRequestConfig['headers'] };

const axios = axios.create();

axios.interceptors.request.use((config: Config) => {
  if (config._originalHeaders) {
    config.headers = config._originalHeaders;
  } else {
    config._originalHeaders = config.headers;
  }
  return config;
});

const interceptor = aws4Interceptor({...});
axios.interceptors.request.use(interceptor);
dblock commented 1 month ago

I fixed this in https://github.com/jamesmbourne/aws4-axios/pull/1631 with a test.