Skip to content

net/http: convert URL credentials to Authorization header for js fetch #56564

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

bored-engineer
Copy link
Contributor

The fetch JS API will refuse to accept URLs that contain credentials:

> fetch("https://user:[email protected]")
TypeError: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials

However the non-JS http.RoundTripper does accept URLs with credentials.
By converting the credentials to an Authorization header, we can have parity.
This header is added only if Authorization header is not already set.

@gopherbot
Copy link
Contributor

This PR (HEAD: af7b54c) has been imported to Gerrit for code review.

Please visit https://go-review.googlesource.com/c/go/+/447916 to see it.

Tip: You can toggle comments from me using the comments slash command (e.g. /comments off)
See the Wiki page for more info

@bored-engineer
Copy link
Contributor Author

For folks that cannot patch all of their http.RoundTripper instances to handle this case, you can implement a similar patch in JS by proxying all fetch invocations:

// Proxy the global 'fetch' function
// TODO: Remove after https://go-review.googlesource.com/c/go/+/447916
globalThis.fetch = new Proxy(globalThis.fetch, {
  // When the function is invoked, modify args as needed
  apply: function (fetch, thisArg, argumentsList) {
    // Extract the input and (optional) init args
    const [input, init = {}] = argumentsList;
    // Parse the input as a URL if it's not already one
    const url = input instanceof URL ? input : new URL(input, location.href);
    // If there are credentials in the URL, add to Authorization header
    if (url.password || url.username) {
      init.headers = init.headers || new Headers();
      init.headers.set(
        "Authorization",
        `Basic ${btoa(url.username + ":" + url.password)}`
      );
      url.username = "";
      url.password = "";
    }
    return fetch.call(thisArg, url, init);
  },
});

@gopherbot
Copy link
Contributor

Message from Damien Neil:

Patch Set 1:

(1 comment)


Please don’t reply on this GitHub thread. Visit golang.org/cl/447916.
After addressing review feedback, remember to publish your drafts!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants