Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Akka ticket #19689
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.headers.HttpCredentials
import akka.http.scaladsl.model.ws.Message
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.{AuthenticationResult, WebSocketDirectives}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Flow
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.io.StdIn
object WebSocketServerBasicAuth extends WebSocketDirectives {
def main(args: Array[String]) {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
case class LdapUser(dn: String, uid: String, givenName: String, surname: String, mail: String)
def myauth(credentials: Option[HttpCredentials]): Future[AuthenticationResult[LdapUser]] = {
Future {
AuthenticationResult.success(LdapUser(dn = "rleibman", uid = "rleibman", givenName = "rleibman", surname = "rleibman", mail = "rleibman"))
}
}
val route =
get {
extractRequest { req =>
authenticateOrRejectWithChallenge(myauth _) { implicit user
path("ws") {
handleWebSocketMessages {
// just echo
Flow[Message]
}
}
}
}
}
val binding = Await.result(Http().bindAndHandle(route, "127.0.0.1", 8080), 3.seconds)
println("Running at 127.0.0.1:8080, press enter to kill server")
StdIn.readLine()
system.terminate()
/*
client
<html>
<head>
<script language="javascript">
var connection = new WebSocket('ws://test:1234@localhost:8080/ws')
connection.onopen = function () { connection.send('Ping') }
connection.onerror = function (error) { console.log('WebSocket Error ', error) }
connection.onmessage = function (e) { console.log('Server: ', e.data) }
</script>
</head>
<body></body>
</html>
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.