Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic authentication with fetch?

People also ask

How do I use Basic Auth in Fetch?

To perform Fetch with HTTP basic auth, simply include the authorization headers in the request. var credentials = btoa("USER:PASSWORD"); var auth = { "Authorization" : `Basic ${credentials}` };

How do I add basic auth to API?

OutSystems allows you to add basic authentication to the requests made to the REST APIs you are exposing. For that, do the following: In the Logic tab, open the Integrations folder. Select the exposed REST API you want to change and set its "Authentication" property to Basic .

How do you pass basic auth in curl?

To send basic auth credentials with Curl, use the "-u login: password" command-line option. Curl automatically converts the login: password pair into a Base64-encoded string and adds the "Authorization: Basic [token]" header to the request.


You are missing a space between Basic and the encoded username and password.

headers.set('Authorization', 'Basic ' + base64.encode(username + ":" + password));

A solution without dependencies.

Node

headers.set('Authorization', 'Basic ' + Buffer.from(username + ":" + password).toString('base64'));

Browser

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

In pure JavaScript you can also use btoa instead of base64.encode():

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

Note that this will only work with ASCII characters.

If you have to handle different encodings, see the linked btoa documentation.


A simple example for copy-pasting into Chrome console:

fetch('https://example.com/path', {method:'GET', 
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));

or with await:

let response = await fetch('https://example.com/path', {method:'GET', 
headers: {'Authorization': 'Basic ' + btoa('login:password')}});
let data = await response.json();
console.log(data);

If you have a backend server asking for the Basic Auth credentials before the app then this is sufficient, it will re-use that then:

fetch(url, {
  credentials: 'include',
}).then(...);