Scala:http4s给予401 Unauthorized相同的请求,可以在curl / req
发布时间:2020-12-16 18:10:14 所属栏目:安全 来源:网络整理
导读:我使用http4s v0.19.0尝试了以下代码: import cats.effect._def usingHttp4s(uri: String,bearerToken: String)(implicit cs: ContextShift[IO]): String = { import scala.concurrent.ExecutionContext import org.http4s.client.dsl.io._ import org.http
我使用http4s v0.19.0尝试了以下代码:
import cats.effect._ def usingHttp4s(uri: String,bearerToken: String)(implicit cs: ContextShift[IO]): String = { import scala.concurrent.ExecutionContext import org.http4s.client.dsl.io._ import org.http4s.headers._ import org.http4s.Method._ import org.http4s._ import org.http4s.client._ import org.http4s.client.middleware._ val blockingEC = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(5)) val middlewares = Seq( RequestLogger[IO](logHeaders = true,logBody = true,redactHeadersWhen = _ => false)(_),FollowRedirect[IO](maxRedirects = 5)(_) ) val client = middlewares.foldRight(JavaNetClientBuilder(blockingEC).create[IO])(_.apply(_)) val req = GET( Uri.unsafeFromString(uri),Authorization(Credentials.Token(AuthScheme.Bearer,bearerToken)) ) client.expect[String](req).unsafeRunSync() } 我收到以下错误: [error] (run-main-0) org.http4s.client.UnexpectedStatus: unexpected HTTP status: 401 Unauthorized [error] org.http4s.client.UnexpectedStatus: unexpected HTTP status: 401 Unauthorized 不仅如此,我的程序永远不会退出(我必须关闭一些客户端!?),即使我连接了一个记录中间件,它也从未打印过请求 我接下来尝试了@ li-haoyi的request库,这没有返回错误: def usingLiHaoyiRequest(uri: String,bearerToken: String): String = requests.get(uri,headers = Iterable("Authorization" -> s"Bearer $bearerToken")).text() 上面的代码适用于相同的uri和相同的baseToken,所以它不能是我的令牌是错误的.为了加倍肯定,我尝试了卷曲: curl -L -H "Authorization: Bearer ${BEARER}" ${URI} 在http4s v0.18.19中也会发生此问题(即使使用显式Json和接受标头): import io.circle.Json def usingHttp4s(uri: String,bearerToken: String): Json = { import org.http4s.client.dsl.io._ import org.http4s.headers._ import org.http4s.Method._ import org.http4s._ import org.http4s.client.blaze.Http1Client import org.http4s.client.middleware._ import org.http4s.circe._ import org.http4s.MediaType._ val program = for { c <- Http1Client[IO]() client = FollowRedirect(maxRedirects = 5)(c) req = GET( Uri.unsafeFromString(uri),bearerToken)),Accept(`application/json`) ) res <- client.expect[Json](req) } yield res program.unsafeRunSync() } 所以我的问题是: >两个请求和卷曲如何工作,但http4s给了我 解决方法
如
gitter room中所述,错误在http4s中,它不会将授权标头转发到重定向,但curl和请求都会转发(只要转发到同一个子域).
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |