11

有谁知道是否可以使用 EventSource 发送基本的 http 身份验证凭据?

4

5 回答 5

4

我正在寻找相同问题的解决方案。这篇文章在这里说:

另一个需要注意的是,据我们所知,您在使用 EventSource 时无法更改 HTTP 标头,这意味着您必须提交一个授权查询字符串参数,其中包含您使用 HTTP Basic Auth 插入的值:您的 base64 编码连接登录名和令牌。

这是帖子中的代码:

// First, we create the event source object, using the right URL.
var url = "https://stream.superfeedr.com/?";
url += "&hub.mode=retrieve";
url += "&hub.topic=http%3A%2F%2Fpush-pub.appspot.com%2Ffeed";
url += "&authorization=anVsaWVuOjJkNTVjNDhjMDY5MmIzZWFkMjA4NDFiMGViZDVlYzM5";

var source = new EventSource(url);

// When the socket has been open, let's cleanup the UI.
source.onopen = function () {
  var node = document.getElementById('sse-feed');
  while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
  }
};

// Superfeedr will trigger 'notification' events, which corresponds
// exactly to the data sent to your subscription endpoint 
// (webhook or XMPP JID), with a JSON payload by default.
source.addEventListener("notification", function(e) {
  var notification = JSON.parse(e.data);
  notification.items.sort(function(x, y) {
    return x.published - y.published;
  });
  notification.items.forEach(function(i) {
    var node = document.getElementById('sse-feed');
    var item = document.createElement("li");
    var t = document.createTextNode([new Date(i.published * 1000), i.title, i.content].join(' '));
    item.appendChild(t);
    node.insertBefore(item, node.firstChild);
    // We add the element to the UI.
  });
});

于 2015-03-27T15:12:53.210 回答
2

如果您谈论 cookie(不是 http auth):

EventSource 使用 http,因此 cookie 与 EventSource 连接请求一起发送。

应该像任何其他 http url 一样支持 Http 身份验证,尽管从规范 CORS+http 身份验证不受支持。

于 2011-10-07T10:06:24.067 回答
1

您可以使用event-source-polyfill添加这样的标题

import { EventSourcePolyfill } from 'event-source-polyfill';

new EventSourcePolyfill(`/api/liveUpdate`, {
  headers: {
    Authorization: `Bearer 12345`,
    'x-csrf-token': `xxx-xxx-xxx`,
  },
});
于 2021-05-05T14:12:06.527 回答
0

EventSource 是关于服务器向客户端发送事件的。我认为您需要双向通信进行身份验证。否则,您将如何发送实际凭据?

然而,WebSockets 可以实现这一点。那是你要找的吗?

更新:

正如4esn0k所指出的,您可以通过使用 cookie 来实现您想要的。Cookie 与浏览器为建立连接而发出的初始请求一起发送。因此,只需确保在启动任何 EventSource 连接之前为 cookie 设置了会话标识符。

于 2011-07-08T16:00:51.360 回答
0

现在有一个 NPM 包来改变 HTTP Header

https://www.npmjs.com/package/eventsource

这个库是 EventSource 客户端的纯 JavaScript 实现。该 API 旨在与 W3C 兼容。

您可以将它与 Node.js 一起使用,或者用作不支持原生 EventSource 的浏览器的浏览器 polyfill。

于 2020-05-01T00:32:35.973 回答