【发布时间】:2022-01-02 07:59:52
【问题描述】:
我找到了不安全的 ktor websocket 服务器 (ws://...) 的文档:
https://ktor.io/docs/creating-web-socket-chat.html#creating-the-chat-client
我找到了安全 ktor http 服务器的文档 (https://...)
https://github.com/ktorio/ktor-documentation/tree/main/codeSnippets/snippets/ssl-embedded-server
但我似乎无法找到或弄清楚如何提供安全的 ktor websocket 服务器 (wss://...)
我宁愿不要在它前面使用像 nginx 这样的 SSL 反向代理。
编辑:这是代码:
import io.ktor.application.*
import io.ktor.http.cio.websocket.*
import io.ktor.network.tls.certificates.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.websocket.*
import java.io.*
fun main() {
val keyStoreFile = File("build/keystore.jks")
val keystore = generateCertificate(
file = keyStoreFile,
keyAlias = "sampleAlias",
keyPassword = "foobar",
jksPassword = "foobar"
)
val environment = applicationEngineEnvironment {
sslConnector(
keyStore = keystore,
keyAlias = "sampleAlias",
keyStorePassword = { "foobar".toCharArray() },
privateKeyPassword = { "foobar".toCharArray() }) {
port = 8443
keyStorePath = keyStoreFile
}
module(Application::module)
}
embeddedServer(Netty, environment).start(wait = true)
}
private fun Application.module() {
install(WebSockets)
routing {
get("/") { // works at https://localhost:8443 in Firefox after approving cert
call.respondText("This is https")
}
webSocket("/chat") { // fails at wss://localhost:8443/chat in Websocket js client with "Firefox can’t establish a connection to the server"
send("This is wss")
}
}
}
【问题讨论】:
-
您可以像配置 HTTP 服务器一样配置它。有关更多信息,请阅读 SSL 和证书文档ktor.io/docs/ssl.html。
-
@AlekseiTirman 我试过使用 sslConnector(...),它配置 https 并且可以工作,但似乎对 websocket 没有任何作用。我在我的问题中添加了代码。
标签: kotlin security encryption websocket ktor