Rorschach
Rorschach

Reputation: 3802

Curl to Javascript

I am making a Chrome Extension that talks to a website via an api. I want it to pass information about a current tab to my website via a cors request.

I have a POST api request already working. It looks like this:

...
var url = "https://webiste.com/api/v1/users/sendInfo"
...
xhr.send(JSON.stringify({user_name:user_name, password:password, info:info}));

Its corresponding curl statement is something like this:

curl -X POST https://website.com/api/v1/users/sendInfo -d '{ username:"username", password:"password", info: "Lot's of info" }' --header "Content-type: application/json

But, this is not as secure as we want. I was told to mirror the curl command below:

curl --basic -u username:password <request url> -d '{ "info": "Lot's of info" }'

But, one cannot just write curl into javascript. If someone could either supply javascript that acts like this curl statement or explain exactly what is going on in that basic option of the curl script I think that I could progress from there.

Upvotes: 2

Views: 5660

Answers (2)

Igor Raush
Igor Raush

Reputation: 15240

The curl command is setting a basic Authorization header. This can be done in JavaScript like

var url = "https://webiste.com/api/v1/users/sendInfo",
    username = "...",
    password = "...";
xhr.open('POST', url, true, username, password);
xhr.send(...);

This encodes the username/password using base 64, and sets the Authorization header.


Edit As arcyqwerty mentioned, this is no more secure than sending username/password in the request body JSON. The advantage of using the basic authentication approach is that it's a standard way of specifying user credentials which integrates well with many back-ends. If you need security, make sure to send your data over HTTPS.

Upvotes: 4

arcyqwerty
arcyqwerty

Reputation: 10675

curl is the curl binary which fetches URLs.

--basic tells curl to use "HTTP Basic Authentication"

-u username:password tells curl supply a given username/password for the authentication. This authentication information is base64 encoded in the request. Note the emphasis on encoded which is different from encrypted. HTTP basic auth is not secure (although it can be made more secure by using an HTTPS channel)

-d tells curl to send the following as the data for the request

You may be able to specify HTTP basic authentication in your request by making the request to https://username:[email protected]/api/v1/users/sendInfo

Upvotes: 1

Related Questions