事件源和基本的HTTP身份验证

14

有人知道如何在EventSource中发送基本的HTTP身份验证凭据吗?

5个回答

7
我正在寻找解决同样问题的方案。这篇文章在此处提到了以下内容:
另一个注意事项是,据我们所知,使用EventSource时无法更改HTTP标头,这意味着您必须提交一个授权查询字符串参数,其值与您使用HTTP基本身份验证插入的值相同:登录和令牌的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.
  });
});


3
现在已经有一个NPM包可以改变HTTP头。

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

这个库是一个纯JavaScript实现的EventSource客户端。API旨在与W3C兼容。您可以将其与Node.js一起使用,也可以作为浏览器的polyfill,用于不支持原生EventSource的浏览器。

2
如果你提到的是cookies(而不是http身份验证):
EventSource使用http协议,因此cookies会随着EventSource连接请求一起发送。
Http身份验证应该像任何其他http url一样被支持,尽管从规范上讲,CORS + http身份验证不受支持。

2
你可以使用event-source-polyfill来添加这样的标头。
import { EventSourcePolyfill } from 'event-source-polyfill';

new EventSourcePolyfill(`/api/liveUpdate`, {
  headers: {
    Authorization: `Bearer 12345`,
    'x-csrf-token': `xxx-xxx-xxx`,
  },
});

很遗憾,它无法工作。请参考以下问题 https://github.com/Yaffle/EventSource/issues/143 - Udhayakumar

-1

EventSource 是关于服务器向客户端发送事件。我认为你需要双向通信来进行身份验证。否则,你怎么会发送实际的凭证呢?

不过,WebSockets 可以实现这一点。那是你所要寻找的吗?

更新:

正如 4esn0k 指出的那样,你可以通过利用 cookie 来实现你想要的功能。cookie 会随着浏览器建立连接时发送的初始请求一起发送。所以,在启动任何 EventSource 连接之前,请确保为 cookie 设置会话标识符。


6
EventSource必须初始化连接并确保保持连接处于打开状态,如果服务器没有关闭,则不会关闭连接;如果服务器正在关闭连接,则尝试无限期重新建立连接。无论如何,EventSource都必须在连接中迈出第一步。EventSource非常适合我的目的,但我希望它在发出请求时发送身份验证信息。 - Miloš Rašić
1
根据规范(http://dev.w3.org/html5/eventsource/),恐怕没有办法发送这些凭据。 - Tower
1
@Tower 我不同意。EventSource只是一个保持连接并具有“text/event-stream”内容类型的HTTP请求。您可以像任何其他HTTP请求一样传递cookie(假设您已经通过身份验证),或者您可以通过查询字符串传递凭据。 - saml

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接