Jeff Sloyer
Jeff Sloyer

Reputation: 4964

307 redirect with Authorization header

In looking at the Go docs for http it looks like the Authorization header is removed when a response is a 307. Obviously it makes sense for almost every case but is there a way not to remove the Authorization header?

Upvotes: 2

Views: 2225

Answers (1)

xarantolus
xarantolus

Reputation: 2029

You can modify your http.Client to add the header again after it has been removed using CheckRedirect:

CheckRedirect func(req *Request, via []*Request) error

Since req is the upcoming request, it can be modified before it is sent. After making the changes, return nil to indicate that the request should still be sent.

Since this is a change to the http client instead of the request, you should check that this redirect is only used for the one URL where you need it (in case you use that client to do other requests).

You client definition could look like this:

http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        // you can check old responses for a status code
        if len(via) != 0 && via[0].Response.StatusCode == http.StatusTemporaryRedirect {
            req.Header.Add("Authorization", "some-value")
        }
        return nil
    },
}

Upvotes: 4

Related Questions