scala - http4s中如何结合AuthedRoutes和HttpRoutes?

标签 scala http4s

http4s 的优先级有什么规则吗AuthedRoutes超过 HttpRoutes当它们都与 <+> 结合时👀

因为这样的组合我收到了 401 authRoute <+> route , 调用时:

GET /non-authed-route

行为发生了变化,当我重新排序路线 route <+> authRoute 时,我收到 200 个相同的请求.

当您需要使用 5 条以上需要组合的路由并且其中一些可能同时包含常规和安全端点时,这可能会更加困惑。

最佳答案

因此,尽管该问题缺少一些上下文信息或代码,但我将假设您的问题与常见问题足够相似:

首先,我假设您的代码具有这种近似形式,并且使用 AuthedRoutes.of 构建。 (定义 here )和 AuthMiddleware :

    val moonAuthedRoutes: AuthedRoutes[F, Int] = AuthedRoutes.of {
      case GET -> / sky / moon as T(42)
    }
    val marsRoutes: HttpRoutes[F] = HttpRoutes.of {
      case GET -> / sky / mars
    }
    // assuming you have your authedMiddleware 
    val moonRoutes = authedMiddleware(moonAuthedRoutes)
    val composedRoutes = moonRoutes <+> marsRoutes

现在,如果您了解所涉及的别名的类型以及解开 Kleisli 后它们归结为什么,将会有所帮助。和 OptionT :

type HttpRoutes[F, T] 
  = Kleisli[OptionT[F, ?], Request[F, T], Response[F]]
  ~~ Request[F] => F[Option[Response[F]]

type AuthedRoutes[F, T] 
  = Kleisli[OptionT[F, ?], AuthedRequest[F, T], Response[F]]
  ~~ (T, Request[F]) => F[Option[Response[F]]

本质上,一个函数接受 HTTP 请求和一些身份验证上下文,并可能给出计算一些响应或没有响应(在 F 中的计算中)。转换这个 AuthedRoutes进入 HttpRoutes ,您使用身份验证中间件:AuthedRoutes 上的包装器接受请求,尝试提取 T从中,如果成功,它将用 T 包装请求并将其传递给 AuthedRoutes , 已完成 in this line of code .如果中间件无法验证请求(即提取 T ),则为 of this line ,它会短路并返回 401 Unauthenticated 响应。

现在,<+>组合首先适用于 moonRoutes 上的请求.如果结果是 some 响应,那么这就是组合路由返回的内容。 仅当 moonRoutes路线(在 <+> 的左侧)返回 F(None)组合会将请求传递给 marsRoutes .特别是,当你给它一个未经验证的请求时,moonRoutes返回一些 401 Unauthenticated响应,这就是composedRoutes返回,但从未将请求传递给 marsRoutes .

如果你交换顺序,写composedRoutes = marsRoutes <+? moonRoutes ,然后在 marsRoutes 中回答对未经身份验证端点的未经身份验证的请求;而经过身份验证的请求首先在 marsRoutes 中进行尝试,失败(给出 F(None) ),然后传递给 moonRoutes ,成功了。

关于scala - http4s中如何结合AuthedRoutes和HttpRoutes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58446033/

相关文章:

scala - sc.textFile 之后的 zipWithIndex 会给出正确的行号吗?

scala - 在 Scala 规范中同步之前/之后的方法?

scala - 将 JValue 转换为 JSON 字符串

algorithm - 了解 Spark CosineSimillarity 输出

scala - 如何使用 http4s 将 cats IO 转换为 Effect

java - 如何在 Scala 中子类化 Exception

scala - 将 circe 与 Http4s 结合使用时用于精炼类型的解码器

swagger - 从 Scala 源代码 (http4s) 生成 Swagger/OpenAPI 规范

scala - http4s 每个请求收到 2 个过早的 EOF 错误

scala - 使用流建模多个函数调用(以安全的 FP 方式)