Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass credentials through a fetch request

I can't pass credentials to avoid of the authentication dialog when GET request is sending as health check to RabbitMQ API. If I pass url with the credentials inside (e.g. http://user:pass@localhost:15672/api/aliveness-test/%2F)

it receives the error below -

rabbitCol.js:12 Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials: http://user:pass@localhost:15672/api/aliveness-test/%2F
    at rabbitColChecking (rabbitCol.js:12)
    at allReqInt (allReqInt.js:5)
    at HTMLAnchorElement.onclick ((index):108)

If I sending this request without the credentials inside the url it's actually sent the request ok but the authentication dialog pop ups in the UI and it's annoying and not a pretty as well.

The request is below -

var fetch = require('node-fetch');

    async function rabbitColChecking() {
        let index;
        const hostsRB = ['http://user:pass@host1:15672/api/aliveness-test/%2F', 'http://user:pass@host2:15672/api/aliveness-test/%2F', 'http://user:pass@host3:15672/api/aliveness-test/%2F', 'http://user:pass@host4:15672/api/aliveness-test/%2F];
        let lengthVal = hostsRB.length;
        for(let hostIndxRB = 0; hostIndxRB < lengthVal; hostIndxRB++) {
            index = hostIndxRB;
            let url = hostsRB[hostIndxRB];
            fetch(url, {method: 'GET', credentials:'same-origin', redirect: 'follow', agent: null, headers: {"Content-Type": "text/plain"}, timeout: 5000}
        ).then(function (hostindxRB, res) {
                handleLedResponseRB(res, hostindxRB);
            }.bind(null, hostIndxRB));
            await sleep(500);
        }
    }

The trigger to send this request is a "onclick" function inside some HTML file.

I've actually tried every solution I saw in the net, but nothing solves this use case.

like image 975
Idan E Avatar asked Aug 20 '17 12:08

Idan E


People also ask

What is credentials in fetch API?

The credentials read-only property of the Request interface indicates whether the user agent should send or receive cookies from the other domain in the case of cross-origin requests.

How do you pass credentials in JavaScript?

btoa() method. // The username and password // DO NOT store credentials in your JS file like this let username = 'myUsername'; let password = '1234'; let auth = btoa(`${username}:${password}`); // Authenticate (dummy API) fetch('https://my-app.com/auth', { headers: { 'Authorization': `Basic ${auth}` } }).

How do I retrieve data from a fetch request?

How do I return a response on Fetch? Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do I fetch with Authorization?

To use basic authentication with Fetch, all you need is a little Base64 encoding and the Authorization header. Try changing the login and password below; values other than “user” and “passwd” will result in a 401 error. Learn new data visualization techniques.


1 Answers

You can send your user name and password with fetch using the Authorization header, like this:

fetch(url, {
    method: 'GET',
    credentials: 'same-origin',
    redirect: 'follow',
    agent: null,
    headers: {
        "Content-Type": "text/plain",
        'Authorization': 'Basic ' + btoa('username:password'),
    },
    timeout: 5000
});

btoa is a function provided by browsers. If you want to use it on the server side, you can require the btoa npm module to do the job.

like image 56
Patrick Hund Avatar answered Oct 03 '22 06:10

Patrick Hund