最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Basic authentication (or any authentication) with fetch - Stack Overflow

programmeradmin3浏览0评论

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' ().

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 municationg 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));
    });

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./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 municationg 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));
    });
Share Improve this question edited Mar 16, 2016 at 18:07 user177800 asked Mar 15, 2016 at 14:44 Andreas SelenwallAndreas Selenwall 5,79511 gold badges47 silver badges60 bronze badges 3
  • What exactly do you mean by "authentication"? What is it that you're trying to do? – Pointy Commented Mar 15, 2016 at 14:45
  • I am using Spring Boot to expose a REST api, and it requires Basic Authentication as I have set it up right now. Basically I want to do a "Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l" ... but before sending the headers my self I just wanted to check if the functionality was built into the fetch api. – Andreas Selenwall Commented Mar 15, 2016 at 14:49
  • 1 As far as I remember, basic auth is just setting headers, so it should be as simple as adding some to the object you pass to the function. – JCOC611 Commented Mar 15, 2016 at 14:51
Add a ment  | 

3 Answers 3

Reset to default 4

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);
                        });

no-cors mode prevents the headers from being anything other than simple headers.

"Authorization" header doesn't fit to simple headers. See more here: https://developer.mozilla/en-US/docs/Web/API/Request/mode

Since it looks like the library you are using is a polyfill for Fetch API, I'm going to work off of the assumption that the syntax should carry through as well.

The samples I found on Mozilla's page indicate that the fetch method signature is fetch('API_ENDPOINT', OBJECT) where object looks like:

myHeaders = new Headers({
  "Authorization": "Basic YW5kcmVhczpzZWxlbndhbGw="
});

var obj = {  
  method: 'GET',
  headers: myHeaders
})

So the method bees:

fetch('http://localhost:8080/timeEntry', obj)
    .then(checkStatus)
    .then(parseJSON)...

I have not tested this code, but it seems consistent with what I was able to find. Hope this points you in the right direction.

发布评论

评论列表(0)

  1. 暂无评论