用来 authenticate 的 Directives


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=





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值