簡體   English   中英

事件源和基本 http 身份驗證

[英]EventSource and basic http authentication

有誰知道是否可以使用 EventSource 發送基本的 http 身份驗證憑據?

我正在尋找相同問題的解決方案。 這篇文章在這里說:

另一個需要注意的是,據我們所知,在使用 EventSource 時,您無法更改 HTTP 標頭,這意味着您必須提交一個授權查詢字符串參數,其值將使用 HTTP登錄名和令牌。

這是帖子中的代碼:

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

EventSource 是關於服務器向客戶端發送事件的。 我認為您需要雙向通信進行身份驗證。 否則,您將如何發送實際憑據?

然而,WebSockets 可以實現這一點。 那是你要找的嗎?

更新:

正如 4esn0k 所指出的,您可以通過使用cookies來實現您想要的。 Cookies 與瀏覽器建立連接的初始請求一起發送。 因此,只需確保在啟動任何 EventSource 連接之前為 cookie 設置了 session 標識符。

如果您談論 cookies(不是 http 身份驗證):

EventSource 使用 http,因此 cookies 與 EventSource 連接請求一起發送。

應該支持 Http 身份驗證,就像任何其他 http url 一樣,盡管不支持 CORS+http 身份驗證。

現在有一個NPM package改HTTP ZBF50D5E661106D0ABE7ZZE6F7

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

這個庫是 EventSource 客戶端的純 JavaScript 實現。 API 旨在與 W3C 兼容。

您可以將它與 Node.js 一起使用,或者作為不支持原生 EventSource 的瀏覽器的瀏覽器 polyfill。

您可以使用event-source-polyfill添加這樣的標題

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM