【问题标题】:Cors in vertx on path with query paramters带有查询参数的路径上顶点中的 Cors
【发布时间】:2021-07-16 19:59:39
【问题描述】:

我有 domainA 和 domainB。

domainA 向 domainB 发送 API。我想添加 Cors 功能和 Vertx 以确保发送 API 的是我的 domainA。 其余的是带有查询参数的 URL。

例如到这个 URL:/hello?queryParam=var.

我想做这样的事情:

router.route(".../hello?queryParam=var").handler(CorsHandler.create("specificOriginDomain")

但我还有另一个 API(在代码中的不同位置)具有相同的 URL,但没有查询参数:“.../hello” 我不想与 Cors 阻止

如何阻止(使用 Cors)与他的查询参数相关的特定 URL?

【问题讨论】:

  • 如果请求有(或没有)查询参数,您想使用 CORS 阻止请求吗? CORS 不是合适的机制。 CORS 关注 跨域 请求。
  • 谢谢,我不清楚,我有 2 个域。我想使用 cors 来确保发送请求的确实是我的网站。但我只想为带有查询参数的请求执行此操作
  • 正如@RainbowDash 提到的,CORS 在这里不是正确的解决方案。 CORS 将帮助您防止您的 clients 被诱骗进行跨源相关攻击,但不会确保只有 domainA 向 domainB 发送请求。任何人都可以像使用 curl 之类的工具一样简单地伪造原始标头。

标签: cors vert.x query-parameters


【解决方案1】:

如果我正确理解目标是只有在有 HTTP 参数的情况下才有CORS。在这种情况下,您需要编写一个自定义处理程序。这是一个简单的例子:

// create the desired CORS handler to check CORS as you desire
// this handler is not be used directly but will be used 
CORSHandler cors = CORSHandler.create(...);

Handler<RoutingContext> myCORSHandler = (ctx) -> {
  if (ctx.request().getParam("var") != null) {
    // your request contains the parameter "var" so
    // we will make it go through the CORS Handler
    cors.handle(ctx);
  } else {
    // the request is "safe" so we ignore the CORS
    // and go to the next handler directly
    ctx.next();
  }
});

// later in your application, just use your CORS handler
Router app = Router.router(vertx);
...
app.route().handler(myCorsHandler);
app.route().handler(ctx -> {
  // depending in the params when you reach here, the CORS
  // have been checked or not...
  // if you want to know which case happened, just add a
  // property to the context in the "if" statement in the
  // custom handler, e.g.: ctx.put("CORS", true)
});

【讨论】:

  • 非常感谢,很有帮助:)
  • 编写处理程序的好方法! ?
【解决方案2】:

虽然您的要求在技术上是可行的,但我必须同意您可能不应该这样做的评论。

让我试着解释一下。您可以在同一条路线上设置两个处理程序,它会起作用:

router.get("hello").handler(CorsHandler.create("specificOriginDomain"));
router.get("hello").handler((req) -> { ... });

但这将对所有路由、查询参数应用相同的逻辑。

此外,CORS 默认是阻塞的。因此,当您指定 CorsHandler 时,您实际上允许来自该域的跨域请求,而不是相反。不过,您的所有请求似乎都来自同一个域。

我建议改为在处理程序中实现与 CORS 无关的逻辑:

router.get("hello").handler((ctx) -> { 

   if (ctx.request().getParam("var") != null) {
      ctx.fail(403);
   }
   else {
      // Continue as usual 
   }
 });

您还可以查看CorsHandler 的实际实现方式:

https://github.com/vert-x3/vertx-web/blob/master/vertx-web/src/main/java/io/vertx/ext/web/handler/impl/CorsHandlerImpl.java#L162

【讨论】:

  • 非常感谢您的回答,我不清楚,我有 2 个域。我想使用 cors 来确保发送请求的确实是我的网站。但我只想为带有查询参数的请求执行此操作
  • 我明白了。不过,您仍然需要自己检查是否有查询参数。 CorsHandler 无法检查。
猜你喜欢
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多