XForwardedHeaderSupport (Reverse Proxy Support)

预计阅读时间:3分钟

此功能使您可以处理反向代理标头,以在原始请求位于代理后面时获取有关原始请求的信息.

  • ForwardedHeaderSupport处理标准的Forwarded标头( RFC 7239
  • XForwardedHeaderSupport处理非标准(但实际上是标准的) X-Forwarded-Host / X-Forwarded-ServerX-Forwarded-ForX-Forwarded-ByX-Forwarded-Proto / X-Forwarded-ProtocolX-Forwarded-SSL / Front-End-Https X-Forwarded-SSL

仅当您具有支持这些标头满足您的请求的反向代理时,才安装这些功能. 在其他情况下,客户端将能够操纵这些标头.

目录:

此功能在io.ktor.features.ForwardedHeaderSupport类中io.ktor.features.ForwardedHeaderSupport ,不需要其他工件.

Usage

这些功能不需要任何特殊配置. 您可以根据反向代理安装这两者中的任何一个,但是由于标准是Forwarded标头,因此应尽可能使用它.

install(ForwardedHeaderSupport)

or

install(XForwardedHeaderSupport)

Request information

您可以在"请求"页面上查看所有可用的请求属性 .

The proxy request information

您可以使用request.local属性读取与代理请求相对应的原始或本地请求信息,从接收的常规标头和套接字属性中读取:

val scheme = request.local.scheme
val version = request.local.version
val port = request.local.port
val host = request.local.host
val uri = request.local.uri
val method = request.local.method
val remoteHost = request.local.remoteHost

The original request information

您可以使用request.origin属性读取原始请求信息,从ForwardedX-Forwarded-*头中读取并回退到原始头,该原始头对应于原始客户端请求:

val scheme = request.origin.scheme // Determined from X-Forwarded-Proto / X-Forwarded-Protocol / X-Forwarded-SSL
val version = request.origin.version
val port = request.origin.port // Determined from X-Forwarded-Host / X-Forwarded-Server
val host = request.origin.host // Determined from X-Forwarded-Host / X-Forwarded-Server
val uri = request.origin.uri
val method = request.origin.method
val remoteHost = request.origin.remoteHost // Determined from X-Forwarded-For

在需要X-Forwarded-By(用于套接字的接口)的情况下,可以使用以下命令访问原始的X-Forwarded属性:

val forwardedValues: List<ForwardedHeaderSupport.ForwardedHeaderValue> = call.attributes[ForwardedHeaderSupport.ForwardedParsedKey]
data class ForwardedHeaderValue(val host: String?, val by: String?, val forParam: String?, val proto: String?, val others: Map<String, String>)

Header description

标准的Forwarded标头如下所示:

Forwarded: by=<identifier>; for=<identifier>; host=<host>; proto=<http|https>
  • by -请求进入代理服务器的接口.
  • for -发起代理中的一个链上的请求和随后的代理客户端.
  • host代理接收的主机请求标头字段.
  • proto指示用于发出请求的协议(通常为" http"或" https").

您可以在MDN文档中阅读有关转发的更多信息.

by  ICOPY.SITE