Basic authentication (or any authentication) with fetch

Viewed 18372

Couldn't find any documentation on this, so before I dig deep in code does anyone out there know how to use basic authentication when making a REST request using 'fetch' (https://github.com/github/fetch).

Just tried the following line, but the header was not set in the request:

  fetch('http://localhost:8080/timeEntry', {
      mode: 'no-cors',
      headers: { 'Authorization': 'Basic YW5kcmVhczpzZWxlbndhbGw=' }
    })
    .then(checkStatus)
    .then(parseJSON)
    .then(function(activities) {
      console.log('request succeeded with JSON response', data);
      dispatch(activitiesFetched(activities, null));
    }).catch(function(error) {
      console.log('request failed', error);
      dispatch(activitiesFetched(null, error));
    });

The username and password is my own first and last name, using curl it works.

If I put { 'Accept' : 'application/test' } Accept is set, just not Authorization... strange.

Just for me to able to continue I added credentials: 'include' which makes the browser to prompt for username and password which is used for communicationg with the REST backend. Just for testing, will use OAuth further on.

  fetch('http://localhost:8080/timeEntry', {
      mode: 'no-cors',
      credentials: 'include'
    })
    .then(checkStatus)
    .then(parseJSON)
    .then(function(activities) {
      console.log('request succeeded with JSON response', data);
      dispatch(activitiesFetched(activities, null));
    }).catch(function(error) {
      console.log('request failed', error);
      dispatch(activitiesFetched(null, error));
    });
3 Answers

Note that if you use fetch with Authorization header you will NOT establish a session. You will have to manually add that header for every request. Navigating to secured path would also not be possible.

So to make this work You should pre-authenticate with XMLHttpRequest. You can do this like so:

                        var authUrl = location.origin + '/secured-path/';
                        var http = new XMLHttpRequest();                        
                        http.open("get", authUrl, false, login, pass);
                        http.send("");
                        if (http.status == 200) {
                            //location.href = authUrl;
                        } else {
                            alert("⚠️ Authentication failed.");
                        }

Note that above is synchronous so you don't need a callback here.

So after doing this you can use fetch without headers e.g. this request should be successful:

                        fetch(authUrl, { 
                            method: 'get',
                        }).then(function(response) {
                            console.log(response);
                        });
Related