spray-hawk is a library that adds Hawk Authentication to Spray.io. It can be used for both server-side (via spray-routing) and client-side (via spray-client).
Current version is 0.3.
- Scala 2.11.x
- Spray 1.3.x
spray-hawk is published to Sonatype OSS and Maven Central. The following example shows how to add a dependency to the latest version to your sbt build definition:
libraryDependencies += "com.ryanbrozo" %% "spray-hawk-lib" % "0.3"
###Server Usage Example:
// Our User model. This needs to extend the HawkUser trait for our UserCredentialsRetriever
// to work
case class User(name: String, key: String, algorithm: HawkHashAlgorithms) extends HawkUser
// Our user credentials retriever. Currently it returns 'Bob' along with his hawk credentials
val userCredentialsRetriever: UserRetriever[User] = { id =>
Future.successful {
if (id == "dh37fgj492je") Some(User("Bob", "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn", HawkHashAlgorithms.HawkSHA256))
else None
}
}
val hawkAuthenticator = HawkAuthenticator("hawk-test", userCredentialsRetriever)
startServer(interface = "localhost", port = 8080) {
// Add Server-Authorization header for response payload validation
withHawkServerAuthHeader(userCredentialsRetriever) {
path("secured") {
authenticate(hawkAuthenticator) { user =>
get {
complete {
s"Welcome to spray, ${user.name}!"
}
} ~
post {
entity(as[String]) { body =>
complete {
s"Welcome to spray, ${user.name}! Your post body was: $body"
}
}
}
}
}
}
}
###Client Usage Example:
val hawkCreds = HawkCredentials("dh37fgj492je", "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn", HawkHashAlgorithms.HawkSHA256)
val pipeline =
addHawkCredentials("hawk-client")(hawkCreds) ~>
sendReceive ~>
unmarshal[String]
val responseFuture = pipeline {
Get("http://localhost:8080/secured")
}
responseFuture onComplete {
case Success(result) =>
println(result)
shutdown()
case util.Failure(error) =>
println(s"Cannot retrieve URL: $error")
shutdown()
}
val hawkCreds = HawkCredentials("dh37fgj492je", "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn", HawkHashAlgorithms.HawkSHA256)
val pipeline =
addHawkCredentials("hawk-client")(hawkCreds, withPayloadValidation = true) ~>
sendReceive ~>
unmarshal[String]
val responseFuture = pipeline {
Post("http://localhost:8080/secured", "Thank you for flying Hawk")
}
responseFuture onComplete {
case Success(result) =>
println(result)
shutdown()
case util.Failure(error) =>
println(s"Cannot retrieve URL: $error")
shutdown()
}
Head towards the Wiki to learn how to use the library inside your project.
- Initial release
This code is open source software licensed under the MIT License