EventSource和基本的http身份验证

Mil*_*šić 9 javascript security html5 server-sent-events

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

Kar*_*thi 7

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

另一个需要注意的是,据我们所知,您在使用 EventSource 时无法更改 HTTP 标头,这意味着您必须提交一个授权查询字符串参数,其中包含您使用 HTTP 基本身份验证插入的值:您的 URL 的 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.
  });
});
Run Code Online (Sandbox Code Playgroud)


Tow*_*wer -1

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

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

更新:

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

  • EventSource 必须初始化连接并保持其打开状态,如果服务器没有关闭它,则永远不关闭它,或者如果服务器关闭它,则尝试无限期地重新建立它。无论哪种方式,EventSource 都必须迈出连接的第一步。EventSource 非常适合我的目的,但我希望它在发出请求时发送身份验证信息。 (6认同)