Vertx SockJs Eventbus 认证

Mar*_*kus 2 websocket event-bus vert.x sockjs

我正在尝试从前端到 vertx 后端建立 sock.js 连接。

我最初的尝试是这样的:

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
  });
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为我需要发送有关 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);
Run Code Online (Sandbox Code Playgroud)

无论我尝试什么,标题字段Authroization始终为空。

在 vertx 中验证 sock.js 连接并注册到 eventbus 请求的标准方法是什么?

ber*_*rkk 7

SockJS 默认使用 WebSockets。您不能使用 JavaScript WebSocket API 添加自定义标头(授权等)。阅读此线程以获取更多解释。

我看到两种方法,如何添加授权:

  1. 只需token在 URL 中添加参数:

    let eb = new EventBus("http://localhost:8080/eventbus?token=" + token);
    
    Run Code Online (Sandbox Code Playgroud)

    这是在服务器上获取它的方法:

    String token = ctx.request().getParam("token");
    
    Run Code Online (Sandbox Code Playgroud)
  2. 连接到服务器后发送授权消息。它可以是一些包含token字段的JSON 对象。

我认为,第一个选项就足够了,但是,就 Event Bus 和 SockJS 而言,第二个选项可能更难实现。

  • 我使用了最新的 SockJs 和 EventBus javascript 包,现在用上面的第一种方法解决了。:) PS 使用:https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.5/sockjs.min.js (3认同)