Using a Self-Signed Certificate

预计阅读时间:3分钟

Ktor允许您创建并使用自签名证书来服务HTTPS或HTTP / 2请求.

此功能在方法中定义io.ktor.network.tls.certificates.generateCertificate在神器io.ktor:ktor-network-tls:$ktor_version .
dependencies { implementation "io.ktor:ktor-network-tls:$ktor_version" }
dependencies { implementation("io.ktor:ktor-network-tls:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-network-tls</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

目录:

要使用Ktor创建自签名证书,必须调用generateCertificate函数.

io.ktor.network.tls.certificates.generateCertificate(File("mycert.jks"))

由于Ktor在启动时需要证书,因此必须在启动服务器之前创建证书.

Create the certificate using gradle

一种可能的选择是在实际运行服务器之前执行生成证书的主类:

CertificateGenerator.kt

您可以使用main方法声明一个类,该方法仅在不存在证书时才生成证书:

package io.ktor.samples.http2

import io.ktor.network.tls.certificates.generateCertificate
import java.io.File

object CertificateGenerator {
    @JvmStatic
    fun main(args: Array<String>) {
        val jksFile = File("build/temporary.jks").apply {
            parentFile.mkdirs()
        }

        if (!jksFile.exists()) {
            generateCertificate(jksFile) // Generates the certificate
        }
    }
}

build.gradle

build.gradle文件中,可以使run任务依赖于generateJks任务,该任务执行生成证书的主类. 例如:

task generateJks(type: JavaExec, dependsOn: 'classes') {
    classpath = sourceSets.main.runtimeClasspath
    main = 'io.ktor.samples.http2.CertificateGenerator'
}

getTasksByName("run", false).first().dependsOn('generateJks')

The HOCON application.conf configuration file

创建HOCON配置文件时,必须添加ktor.deployment.sslPortktor.security.ssl属性来定义ssl端口和keyStore:

resources/application.conf :

ktor {
    deployment {
        port = 8080
        sslPort = 8443
        watch = [ http2 ]
    }

    application {
        modules = [ io.ktor.samples.http2.Http2ApplicationKt.main ]
    }

    security {
        ssl {
            keyStore = build/temporary.jks
            keyAlias = mykey
            keyStorePassword = changeit
            privateKeyPassword = changeit
        }
    }
}

Ktor normal module

之后,您可以编写一个普通的普通Ktor模块:

Module.kt
package io.ktor.samples.http2

import io.ktor.application.*
import io.ktor.features.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.util.*
import java.io.*

fun Application.main() {
    install(DefaultHeaders)
    install(CallLogging)
    install(Routing) {
        get("/") {
            call.push("/style.css")

            call.respondText("""
                <!DOCTYPE html>
                <html>
                    <head>
                        <link rel="stylesheet" type="text/css" href="/style.css">
                    </head>
                    <body>
                        <h1>Hello, World!</h1>
                    </body>
                </html>
            """.trimIndent(), contentType = ContentType.Text.Html)
        }

        get("/style.css") {
            call.respondText("""
                h1 { color: olive }
            """, contentType = ContentType.Text.CSS)
        }
    }
}

Accessing your server

然后,您可以指向https://127.0.0.1:8443/来访问您的服务器. 由于这是一个自签名证书,因此您的浏览器可能会警告您有关无效的证书,因此您必须禁用该警告.

Full example

Ktor在此处提供了一个使用自签名证书的完整示例:

https://github.com/ktorio/ktor/tree/08b173e02fe9a9dbee39f48e7162e6ea7a1f8b16/ktor-samples/ktor-samples-ssl-http2

by  ICOPY.SITE