authenticate 这个Directives 使用了http的
WWW-Authenticate
来实现认证的功能,这个没怎用,百度了下
http://blog.163.com/hongshaoguoguo@126/blog/static/18046981201322384241640/
创建authenticate ,authenticate 跟route构建是不同个线程的
def authenticator(userPass: Option[UserPass]): Future[Option[String]] = Future {
//检查用户
if (userPass.exists(up => up.user == "admin" && up.pass == "admin")) Some(userPass.get.user)
else None
}
val route = sealRoute {
path("secured") {
authenticate(BasicAuth(authenticator _, realm = "secure site")) { userName =>
complete(s"The user is '$userName'")
}
}
}
定义跟Directives 的使用一样
注意的是这里
/**
* "Seals" a route by wrapping it with exception handling and rejection conversion.
*/
def sealRoute(route: Route)(implicit eh: ExceptionHandler, rh: RejectionHandler): Route =
(handleExceptions(eh) & handleRejections(sealRejectionHandler(rh)))(route)
整个代码
import akka.actor.{Props, ActorSystem}
import akka.io.IO
import akka.util.Timeout
import spray.can.Http
import spray.routing._
import spray.http._
import spray.routing.authentication.{UserPass, BasicAuth}
import scala.concurrent.duration._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
object ActorTest5 extends App{
implicit val system = ActorSystem("mySystem")
val se = system.actorOf(Props[MyService2])
implicit val timeout = Timeout(5.seconds)
IO(Http) ! Http.Bind(se,interface = "localhost",port=8080)
}
class MyService2 extends HttpServiceActor {
def authenticator(userPass: Option[UserPass]): Future[Option[String]] = Future {
//检查用户
if (userPass.exists(up => up.user == "admin" && up.pass == "admin")) Some(userPass.get.user)
else None
}
val route = sealRoute {
path("secured") {
authenticate(BasicAuth(authenticator _, realm = "secure site")) { userName =>
complete(s"The user is '$userName'")
}
}
}
def receive = runRoute(route)
}
抓包分析
由于wireshark无法抓取本地连接,我们修改url,把他发给百度,让后截取包分析
重要是这句
Authorization: Basic YWRtaW46YWRtaW4=