Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request with URL that includes credentials

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

curl -XPOST -d "grant_type=password" -d "[email protected]" \
    -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&[email protected]&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?

like image 728
CptRivaille Avatar asked Jul 12 '17 20:07

CptRivaille


People also ask

How do you embed credentials in URL?

Add the Link to Your Credential View PageNavigate to the credential view of the relevant credential. Copy the URL in the browser search bar. Navigate back to the webpage editor that you are using to embed the credential. Paste the URL you just copied into the 'Link to' option of your embedded badge and save.

How do I add credentials to http request?

We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL.

What is HTTP request credentials?

Credentials are cookies, authorization headers, or TLS client certificates. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple GET requests are not preflighted.

How do you use fetch with credentials?

To cause browsers to send a request with credentials included on both same-origin and cross-origin calls, add credentials: 'include' to the init object you pass to the fetch() method. Note: Access-Control-Allow-Origin is prohibited from using a wildcard for requests with credentials: 'include' .


1 Answers

You can't use the https://user:[email protected] 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).

like image 182
Will Munn Avatar answered Sep 30 '22 19:09

Will Munn