Redirect HTTP requests to HTTPS

预计阅读时间:2分钟

此功能将使所有受影响的HTTP调用在处理该调用之前执行重定向到其HTTPS副本.

默认情况下,重定向为301 Moved Permanently ,但可以将其配置为302 Found重定向.

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

Usage

fun Application.main() {
    install(HttpsRedirect)
    // install(XForwardedHeaderSupport) // Required when behind a reverse-proxy
}

上面的代码使用默认配置安装HttpsRedirect功能.

在使用反向代理后,您将需要安装ForwardedHeaderSupportXForwardedHeaderSupport功能,以便HttpsRedirect功能正确检测HTTPS请求.

Configuration

fun Application.main() {
    install(HttpsRedirect) {
        // The port to redirect to. By default 443, the default HTTPS port. 
        sslPort = 443
        // 301 Moved Permanently, or 302 Found redirect.
        permanentRedirect = true
    }
}

Testing

应用此功能会更改测试的工作方式. 应用此功能后,您执行的每个handleRequest都会导致重定向响应. 在大多数情况下,这可能不是您想要的,因为该行为已经过测试.

XForwardedHeaderSupport trick

该测试所示,您可以安装XForwardedHeaderSupport功能,并将addHeader(HttpHeaders.XForwardedProto, "https")标头添加到请求中.

@Test
fun testRedirectHttps() {
    withTestApplication {
        application.install(XForwardedHeaderSupport)
        application.install(HttpsRedirect)
        application.routing {
            get("/") {
                call.respond("ok")
            }
        }


        handleRequest(HttpMethod.Get, "/", {
            addHeader(HttpHeaders.XForwardedProto, "https")
        }).let { call ->
            assertEquals(HttpStatusCode.OK, call.response.status())
        }
    }
}

Do not install the feature when testing or uninstall it

卸载它:

application.uninstall(HttpsRedirect)

首先防止安装:

// The function referenced in the application.conf
fun Application.mymodule() {
    mymoduleConfigured()
}

// The function referenced in the tests
fun Application.mymoduleForTesting() {
    mymoduleConfigured(installHttpsRedirect = false)
}

fun Application.mymoduleConfigured(installHttpsRedirect: Boolean = true) {
    if (installHttpsRedirect) {
        install(HttpsRedirect)
    }
    // ...
}

在这种情况下,您还可以有一个单独的测试,该测试调用mymodule而不是mymoduleForTesting来验证是否已安装HttpsRedirect功能以及您在测试中未执行的其他操作.

I get an infinite redirect when using this feature

您是否安装了XForwardedHeaderSupportForwardedHeaderSupport功能? 检查此常见问题解答条目以获取更多详细信息.

by  ICOPY.SITE