13

I'm trying to fetch a curl and get a JSON from an API.

curl -XPOST -d "grant_type=password" -d "username=admin@admin.admin" \
    -d "password=admin" "web_app@localhost:8081/oauth/token"

When I use the curl in terminal everything works fine but trying it with a fetch I get the error message mentioned at the bottom.

fetch("http://web_app@localhost:8081/oauth/token", {
        credentials: 'include',
        body: "grant_type=password&username=admin@admin.admin&password=admin",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        method: "POST"
    }

This is the error I get:

TypeError: http://web_app@localhost:8081/oauth/token is an url with embedded credentials.

Is the fetch I did wrong?

sideshowbarker
  • 72,859
  • 23
  • 167
  • 174
CptRivaille
  • 139
  • 1
  • 1
  • 4

1 Answers1

21

You can't use the https://user:pass@host.com form, you need to set the Authorization http Header:

var headers = new Headers();

headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
fetch('https://host.com', {headers: headers})

Where btoa encodes 'user:pass' to base64 encoded string. You can find btoa function availability on MDN (in short: it works on IE 10 and above).

Nux
  • 8,068
  • 5
  • 52
  • 68
Will Munn
  • 6,323
  • 4
  • 24
  • 28
  • 7
    What is the reason for this? – felixfbecker Dec 06 '18 at 00:32
  • @felixfbecker I'm not 100% sure but it could be b/c of security reasons... you aren't allowed to store auth-url into the cache storage api. and if the service worker could read the `request.url` then that would also be reviled in the javascript context, but what is stopping u from reading the headers? I also would like to know the exact reason for this disallowance – Endless Sep 07 '21 at 09:15