2017-06-06 111 views
0

我試圖讓從前端至後端vertx一個sock.js連接。Vertx SockJs Eventbus認證

我最初的嘗試是這樣的:

let token = '<the token>'; 
let data = {'Authorization' : 'Bearer ' + token}; 
let eb = new EventBus("http://localhost:8080/eventbus"); 
    eb.onopen = function() { 
    eb.registerHandler('notifications', data, (err, msg) => { 
    // handle the response 
    }); 
} 

這不工作,因爲我需要發送的EventBus創建權威性的數據,即使官方sock.js文檔指出,這是不支持的。顯然現在發送new EventBus("http://localhost:9090/eventbus", data)也不起作用。

https://github.com/sockjs/sockjs-node#authorisation

我這個後臺處理程序:

final BridgeOptions bridgeOptions = new BridgeOptions() 
    .addOutboundPermitted(new PermittedOptions().setAddress("notifications")) 

final SockJSHandler sockJSHandler = SockJSHandler.create(vertx).bridge(bridgeOptions, event -> { 
    event.complete(true); 
}); 

router.route("/eventbus/*").handler(ctx -> { 
    String token = ctx.request().getHeader("Authorization"); // null 
}); 
router.route("/eventbus/*").handler(sockJSHandler); 

無論我試過的頭字段Authroization總是空。

什麼是認證sock.js連接和註冊中vertx的eventbus要求的標準呢?

+0

您是否檢查過Vert.x Web文檔的[要求授權消息](http://vertx.io/docs/vertx-web/java/#_requiring_authorisation_for_messages)部分? – tsegismont

+0

是的,我讀過了整個vertx文檔 – Markus

+0

確定。我問,因爲您的代碼片段看起來不像您使用Vert.x Web授權功能。 – tsegismont

回答

2

SockJS默認使用的WebSockets。您不能使用JavaScript WebSocket API添加自定義標頭(授權等)。請閱讀thread以獲取更多解釋。

我看到2種方式,你如何添加授權:

  1. 只需token參數添加到URL:

    let eb = new EventBus("http://localhost:8080/eventbus?token=" + token); 
    

    ,這裏是你如何能得到它的服務器上:

    連接到服務器後
    String token = ctx.request().getParam("token"); 
    
  2. 發送授權消息。它可以是一些JSON對象,其中包含token字段。

我認爲,第一種選擇是足夠的,但是,第二人能夠更難事件總線和SockJS方面來實現。

+0

不幸的是,在sockJS中不允許查詢參數('只有基本的URL在SockJS'中被支持)。 對於你的第二種方法:應該可以工作,但我想有更好的方法來做到這一點,因爲有了這個,你將無法使用標準的vertex * AuthHandlers,比如'router.route(「/ eventbus/*「)。handler(jwtAuthHandler);'(或者像我上面腳本中的測試處理程序那樣的類似方式) – Markus

+0

您仍然可以使用URL如'/ eventbus /:token'。不確定,如果有另一種更簡單的方法來做到這一點。 – berserkk

+0

我不明白爲什麼,但是是的,好像我必須根據你的解決方案做一些破解。謝謝 – Markus

0

我想,以確保網絡插口採用CORS檢查

跨源資源共享將被要求允許資源的安全機制,最好的辦法

router.route().handler(CorsHandler.create(your host origin path).allowCredentials(true)); 

我們可以添加更多的安全層也採用sockjs:

允許進/出事件總線橋爲指定的地址事件

BridgeOptions opts = new BridgeOptions() 
      .addInboundPermitted(new PermittedOptions().setAddressRegex(Constants.INBOUND_REGEXP)); 
+0

,雖然不幫助認證,但? – Markus

+0

你在說CORS檢查嗎? – Flash

+0

我想驗證和授權使用sock.js的用戶,具有標題的標準休息方式不起作用。上面提出的解決方案或類似的東西(請參閱sock.js auth自述文件)的作品,但都覺得很hacky。我不知道你的CORS解決方案如何解決這個問題? – Markus